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 :
def extract_nth_element(test_list, n):
result = list(map (lambda x:(x[n]), test_list))
return result
students = [('Greyson Fulton', 98, 99), ('Brady Kent', 97, 96), ('Wyatt Knott', 91, 94), ('Beau Turnbull', 94, 98)]
print ("Original list:")
print(students)
n = 0
print("\nExtract nth element ( n =",n,") from the said list of tuples:")
print(extract_nth_element(students, n))
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]
Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
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 Python skills with w3resource's quiz
Python: Tips of the Day
Given a predicate function, fn, and a prop string, this curried function will then take an object to inspect by calling the property and passing it to the predicate:
Example:
def tips_check_prop(fn, prop): return lambda obj: fn(obj[prop]) check_age = tips_check_prop(lambda x: x >= 25, 'age') user = {'name': 'Owen', 'age': 25} print(check_age(user))
Output:
True
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework