Python: Extract the nth element from a given list of tuples using lambda
Python Lambda: Exercise-36 with Solution
Write a Python program to extract the nth element from a given list of tuples using lambda.
Sample Solution:
Python Code :
# Define a function 'extract_nth_element' that extracts the nth element from each tuple in a list
def extract_nth_element(test_list, n):
# Use the 'map' function with a lambda to extract the nth element from each tuple in 'test_list'
result = list(map(lambda x: x[n], test_list))
# Return the resulting list
return result
# Create a list of tuples 'students' containing names and two additional elements for each student
students = [
('Greyson Fulton', 98, 99),
('Brady Kent', 97, 96),
('Wyatt Knott', 91, 94),
('Beau Turnbull', 94, 98)
]
# Print the original list of tuples 'students'
print("Original list:")
print(students)
# Extract the 0th element from each tuple and print the result
n = 0
print("\nExtract nth element (n =", n, ") from the said list of tuples:")
print(extract_nth_element(students, n))
# Extract the 2nd element from each tuple and print the result
n = 2
print("\nExtract nth element (n =", n, ") from the said list of tuples:")
print(extract_nth_element(students, n))
Sample Output:
Original list: [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)] Extract nth element ( n = 0 ) from the said list of tuples: ['Greyson Fulton', 'Brady Kent', 'Wyatt Knott', 'Beau Turnbull'] Extract nth element ( n = 2 ) from the said list of tuples: [99, 96, 94, 98]
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to check whether a specified list is sorted or not using lambda.
Next: Write a Python program to sort a list of lists by a given index of the inner list using lambda.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/lambda/python-lambda-exercise-36.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics