Python | Get first index values in tuple of strings
Last Updated :
24 Mar, 2023
Yet another peculiar problem which might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This articles solves problem of extracting only the first index element of each string in tuple. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehension Almost every problem can be solved using list comprehension as a shorthand to naive approach and this problem isn’t an exception. In this, we just iterate through each list picking just the 0th index element to build the resultant list.
Python3
test_tuple = ( 'GfG' , 'for' , 'Geeks' )
print ("The original tuple : " + str (test_tuple))
res = list (sub[ 0 ] for sub in test_tuple)
print ("The first index string character list : " + str (res))
|
Output :
The original tuple : ('GfG', 'for', 'Geeks')
The first index string character list : ['G', 'f', 'G']
Time complexity: O(n), where n is the length of the tuple.
Auxiliary space: O(n), as we are creating a new list to store the first character of each string in the tuple.
Method #2 : Using next() + zip() This particular task can also be performed using the combination of above two in more efficient way, using the iterators to do this task. The zip function can be used bind together the string elements.
Python3
test_tuple = ( 'GfG' , 'for' , 'Geeks' )
print ("The original tuple : " + str (test_tuple))
res = list ( next ( zip ( * test_tuple)))
print ("The first index string character list : " + str (res))
|
Output :
The original tuple : ('GfG', 'for', 'Geeks')
The first index string character list : ['G', 'f', 'G']
Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using next() + zip() which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #3 : Using the map() function and a lambda function:
Using the map() function and a lambda function to extract the first index of each string in test_tuple
Python3
test_tuple = ( 'GfG' , 'for' , 'Geeks' )
print ( "The original tuple : " + str (test_tuple))
res = list ( map ( lambda x: x[ 0 ], test_tuple))
print ( "The first index string character list : " + str (res))
|
Output
The original tuple : ('GfG', 'for', 'Geeks')
The first index string character list : ['G', 'f', 'G']
Time complexity: O(n)
Auxiliary Space: O(n) for storing result
Method#4: Using for loop
Python3
test_tuple = ( 'GfG' , 'for' , 'Geeks' )
print ( "The original tuple : " + str (test_tuple))
res = []
for string in test_tuple:
res.append(string[ 0 ])
print ( "The first index string character list : " + str (res))
|
Output
The original tuple : ('GfG', 'for', 'Geeks')
The first index string character list : ['G', 'f', 'G']
Time complexity: O(n)
Auxiliary Space: O(n)
Method #5: using re module
Step-by-step algorithm for implementing
- Import the required module, re.
- Initialize a tuple.
- Print the original tuple.
- Initialize an empty list, result, which will store the first index string character list.
- Loop through each string in the test_tuple.
- Using the match() method from the re module, find the first word character of the string.
- Store the first index in the first_index variable.
- Append the first_index to the result list.
- Print the result list.
Python3
import re
test_tuple = ( 'GfG' , 'for' , 'Geeks' )
print ( "The original tuple : " + str (test_tuple))
result = []
for string in test_tuple:
match = re.match(r '(\w)' , string)
first_index = match.group( 0 )
result.append(first_index)
print ( "The first index string character list : " + str (result))
|
Output
The original tuple : ('GfG', 'for', 'Geeks')
The first index string character list : ['G', 'f', 'G']
Time complexity: O(nk), where n is the length of the tuple and k is the length of the longest string in the tuple. The regular expression match operation is O(k) and it is performed n times.
Auxiliary space: O(n), where n is the length of the tuple. The result list stores n elements. The first_index variable is reused for each string in the tuple.
Similar Reads
Get Index of Values in Python Dictionary
Dictionary values are lists and we might need to determine the position (or index) of each element within those lists. Since dictionaries themselves are unordered (prior to Python 3.7) or ordered based on insertion order (in Python 3.7+), the concept of "index" applies to the valuesâspecifically whe
3 min read
How to Get Index of a Substring in Python?
To get index of a substring within a Python string can be done using several methods such as str.find(), str.index(), and even regular expressions. Each approach has its own use case depending on the requirements. Letâs explore how to efficiently get the index of a substring. The simplest way to get
2 min read
Creating Sets of Tuples in Python
Tuples are an essential data structure in Python, providing a way to store ordered and immutable sequences of elements. When combined with sets, which are unordered collections of unique elements, you can create powerful and efficient data structures for various applications. In this article, we wil
3 min read
Find the Index of a Substring in Python
Finding the position of a substring within a string is a common task in Python. In this article, we will explore some simple and commonly used methods to find the index of a substring in Python. Using str.find() The find() method searches for the first occurrence of the specified substring and retur
3 min read
Python - Summation of tuple dictionary values
Sometimes, while working with data, we can have a problem in which we need to find the summation of tuple elements that are received as values of dictionary. We may have a problem to get index wise summation. Letâs discuss certain ways in which this particular problem can be solved. Method #1: Using
4 min read
Python | Get first element with maximum value in list of tuples
In Python, we can bind structural information in form of tuples and then can retrieve the same. But sometimes we require the information of tuple corresponding to maximum value of other tuple indexes. This functionality has many applications such as ranking. Let's discuss certain ways in which this
4 min read
Convert List of Tuples to List of Strings - Python
The task is to convert a list of tuples where each tuple contains individual characters, into a list of strings by concatenating the characters in each tuple. This involves taking each tuple, joining its elements into a single string, and creating a new list containing these strings. For example, gi
3 min read
Python - Get Nth column elements in Tuple Strings
Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the
8 min read
Convert List Of Tuples To Json String in Python
We have a list of tuples and our task is to convert the list of tuples into a JSON string in Python. In this article, we will see how we can convert a list of tuples to a JSON string in Python. Convert List Of Tuples To Json String in PythonBelow, are the methods of Convert List Of Tuples To Json St
3 min read
Python - Unpacking Values in Strings
Given a dictionary, unpack its values into a string. Input : test_str = "First value is {} Second is {}", test_dict = {3 : "Gfg", 9 : "Best"} Output : First value is Gfg Second is Best Explanation : After substitution, we get Gfg and Best as values. Input : test_str = "First value is {} Second is {}
3 min read