If it is required to extract the rear element from a list of tuples, it can be done using list comprehension and negative indexing.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A list of tuple basically contains tuples enclosed in a list.
Below is a demonstration of the same −
Example
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 = [lis[-1] for lis in my_list] print ("The list of tuples with only rear tuple element is : " ) print(my_result)
Output
The list of tuples is : [('Will', 67, 45), ('Jam', 34, 56), ('Pow', 99, 123), ('Nyk', 0, 56)] The list of tuples with only rear tuple element is : [45, 56, 123, 56]
Explanation
- A list of tuples is created, and is displayed on the console.
- The list comprehension is used to iterate through the list of tuples, and the last element is accessed using negative indexing.
- This operation is stored in a variable.
- This variable is the output that is displayed on the console.