Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Rear element extraction from list of tuples records in Python
When working with a list of tuples, you may need to extract the last (rear) element from each tuple. Python provides several approaches to accomplish this task efficiently.
A list of tuples is a collection where each element is a tuple containing multiple values. For example, [('Will', 67, 45), ('Jam', 34, 56)] contains tuples with three elements each.
Using List Comprehension with Negative Indexing
The most Pythonic way is to use list comprehension with negative indexing. The index -1 always refers to the last element in a sequence ?
my_list = [('Will', 67, 45), ('Jam', 34, 56), ('Pow', 99, 123), ('Nyk', 0, 56)]
print("The list of tuples is:")
print(my_list)
my_result = [tup[-1] for tup in my_list]
print("The rear elements extracted:")
print(my_result)
The list of tuples is:
[('Will', 67, 45), ('Jam', 34, 56), ('Pow', 99, 123), ('Nyk', 0, 56)]
The rear elements extracted:
[45, 56, 123, 56]
Using map() Function
You can also use the map() function with a lambda to extract rear elements ?
my_list = [('Will', 67, 45), ('Jam', 34, 56), ('Pow', 99, 123), ('Nyk', 0, 56)]
rear_elements = list(map(lambda tup: tup[-1], my_list))
print("Using map() function:")
print(rear_elements)
Using map() function: [45, 56, 123, 56]
Using operator.itemgetter()
The operator.itemgetter() provides another approach for extracting specific elements ?
from operator import itemgetter
my_list = [('Will', 67, 45), ('Jam', 34, 56), ('Pow', 99, 123), ('Nyk', 0, 56)]
rear_elements = list(map(itemgetter(-1), my_list))
print("Using itemgetter:")
print(rear_elements)
Using itemgetter: [45, 56, 123, 56]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Most common cases |
| map() with lambda | Medium | Fast | Functional programming style |
| itemgetter() | Medium | Fastest | Large datasets |
Conclusion
List comprehension with negative indexing [tup[-1] for tup in my_list] is the most readable and commonly used approach. For performance-critical applications, consider using operator.itemgetter().
