We are given tuples in list we need to access Nth elements from tuples. For example, we are having a list l = [(1, 2), (3, 4), (5, 6)] we need to access the Nth element from tuple suppose we need to access n=1 or 1st element from every tuple present inside list so that in this case the output should be [2, 4, 6].
Using Indexing
To access the nth element from tuples in a list use indexing to refer to both tuple and element first index accesses tuple and second index accesses the element within tuple.
l = [(1, 2), (3, 4), (5, 6)]
n = 1
# Use list comprehension to extract the nth element from each tuple
r = [t[n] for t in l]
print(r)
Output
[2, 4, 6]
Explanation:
- Code uses list comprehension to iterate over each tuple in list l and extracts the nth element from each tuple by indexing t[n].
- Result is a new list r that contains nth element from each tuple.
Using List Comprehension
List comprehension is used to iterate through each tuple in list and access the nth element. It generates a new list with nth element from each tuple.
l = [(1, 2), (3, 4), (5, 6)]
n = 1
# Use list comprehension to extract the nth element from each tuple
r = [t[n] for t in l]
print(r)
Output
[2, 4, 6]
Explanation:
- Code uses list comprehension to iterate through each tuple in the list
land extract the element at indexn(which is 1) from each tuple. - It creates a new list
rcontaining extracted elements.
Using map()
map() function in Python applies a given function to each item of an iterable and returns an iterator containing the results. When working with a list of tuples.
a = [(1, 2), (3, 4), (5, 6)]
n = 1
# Use map() to extract the nth element from each tuple
res = list(map(lambda t: t[n], a))
print(res)
Output
[2, 4, 6]
Explanation:
map()function applies a lambda function to each tuple in the lista, extracting the element at indexn(in this case, the second element of each tuple).list()function converts the mapped result into a list, resulting in[2, 4, 6]which contains the second elements from all tuples.