While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data. Lets discuss certain ways how one can achieve solutions to this problem.
Method #1 : Using list comprehension List comprehension is the simplest way in which this problem can be solved. We can just iterate over only the specific index value in all the index and store it in a list and print it after that.
Python3
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ("The original list is : " + str (test_list))
res = [lis[ 1 ] for lis in test_list]
print (" List with only nth tuple element (i.e names) : " + str (res))
|
Output :
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
List with only nth tuple element (i.e names) : ['Rash', 'Varsha', 'Kil']
Time complexity: O(n), where n is the number of tuples in the input list.
Auxiliary space: O(n), where n is the number of tuples in the input list.
Method #2 : Using map() + itemgetter() map() coupled with itemgetter() can perform this task in more simpler way. map() maps all the element we access using itemgetter() and returns the result.
Python3
from operator import itemgetter
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ("The original list is : " + str (test_list))
res = list ( map (itemgetter( 1 ), test_list))
print (" List with only nth tuple element (i.e names) : " + str (res))
|
Output :
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
List with only nth tuple element (i.e names) : ['Rash', 'Varsha', 'Kil']
Method #3 : Using zip() The most conventional and pythonic way to perform this particular task is using this function. This collects all the nth tuple elements into a single container and returns the result. This only works for Python 2.
Python
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ("The original list is : " + str (test_list))
res = list ( zip ( * test_list)[ 1 ])
print (" List with only nth tuple element (i.e names) : " + str (res))
|
Output :
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
List with only nth tuple element (i.e names) : ['Rash', 'Varsha', 'Kil']
Method #4 : Using map() + lambda
To access the nth element of each tuple in a list using a lambda function, you can define a lambda function that returns the nth element of each tuple, and then use the map function to apply this lambda function to each tuple in the list.
Here is an example of how you can do this:
Python3
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is:" , test_list)
n = 1
res = list ( map ( lambda x: x[n], test_list))
print ( "List with only nth tuple element:" , res)
|
Output
The original list is: [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
List with only nth tuple element: ['Rash', 'Varsha', 'Kil']
Time complexity: O(n), since it involves a single pass through the list. It uses the map function and a lambda function to access the nth element of each tuple, but does not require any additional modules.
Auxiliary space: O(n), since it requires the creation of a new list to store the result.
Method #5: Using a for loop
Step-by-step approach:
- Initialize an empty list to store the nth element of each tuple.
- Loop through each tuple in the given list.
- Append the nth element of the current tuple to the empty list.
- Return the resulting list.
Below is the implementation of the above approach:
Python3
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is:" , test_list)
n = 1
res = []
for tup in test_list:
res.append(tup[n])
print ( "List with only nth tuple element:" , res)
|
Output
The original list is: [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
List with only nth tuple element: ['Rash', 'Varsha', 'Kil']
Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), where n is the number of tuples in the list.
Method 6: Using reduce()
- Import the reduce() function from the functools module: from functools import reduce
- Initialize a list of tuples: test_list = [(1, ‘Rash’, 21), (2, ‘Varsha’, 20), (3, ‘Kil’, 19)]
- Print the original list: print(“The original list is : ” + str(test_list))
- Choose which nth tuple element you want to extract and assign it to the variable n: n = 1
- Use the reduce() function to extract the nth tuple element from each tuple in the list: res = reduce(lambda acc, tup: acc + [tup[n]], test_list, [])
- Print the result: print(“List with only nth tuple element (i.e names) : ” + str(res))
Python3
from functools import reduce
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is : " + str (test_list))
n = 1
res = reduce ( lambda acc, tup: acc + [tup[n]], test_list, [])
print ( "List with only nth tuple element (i.e names) : " + str (res))
|
Output
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
List with only nth tuple element (i.e names) : ['Rash', 'Varsha', 'Kil']
Time complexity:The time complexity of Method #7 is O(n), where n is the length of the input list test_list.
The auxiliary space complexity of Method #7 is O(n), where n is the length of the input list test_list.
Method #7 : Using numpy.array(), and then fancy indexing to get the nth column
We will use numpy.array() function and fancy indexing to get the nth tuple element. We will convert the list of tuples to a 2D numpy array using numpy.array(), and then we will use fancy indexing to get the nth column (which represents the nth tuple element) from the array. Finally, we will convert the resulting 1D numpy array to a list.
- Import numpy module.
- Initialize the list of tuples.
- Convert the list of tuples to a 2D numpy array using numpy.array() function.
- Extract the nth column (which represents the nth tuple element) from the array using fancy indexing.
- Convert the resulting 1D numpy array to a list.
- Print the original list and the list with only the nth tuple element.
Python3
import numpy as np
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is : " + str (test_list))
arr = np.array(test_list)
n = 1
res_arr = arr[:, n]
res = res_arr.tolist()
print ( "List with only nth tuple element (i.e names) : " + str (res))
|
Output:
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
List with only nth tuple element (i.e names) : ['Rash', 'Varsha', 'Kil']
Time complexity: O(n), where n is the number of tuples in the input list. The numpy.array() function has a time complexity of O(n), where n is the number of elements in the input list. Fancy indexing also has a time complexity of O(n), where n is the number of elements in the array. Converting the resulting 1D numpy array to a list has a time complexity of O(n) as well.
Space complexity: O(n), where n is the number of tuples in the input list. The numpy.array() function creates a 2D numpy array of size n x 3, where n is the number of tuples in the input list. The resulting 1D numpy array also has a size of n. Converting the resulting 1D numpy array to a list also creates a list of size n. Therefore, the total space complexity is O(n + n + n), which simplifies to O(n).
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!