Given a list of lists, write a Python program to extract the last element of each sublist in the given list of lists.
Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : [3, 5, 9] Input : [['x', 'y', 'z'], ['m'], ['a', 'b'], ['u', 'v']] Output : ['z', 'm', 'b', 'v']
Approach #1 : List comprehension
[3, 5, 9]
Approach #2 : Using zip and unpacking(*) operator
This method uses zip with * or unpacking operator which passes all the items inside the ‘lst’ as arguments to zip function. There is a little trick with extracting last item of list, Instead of using direct zip, use the reversed list iterators.
(3, 5, 9)
Another way of using
zip is to use it with Python
reversed as function.
Approach #3 : Using
[3, 5, 9]
- Python | Get first element of each sublist
- Python | Getting sublist element till N
- Python | Multiply each element in a sublist by its index
- Python | Sort a list according to the second element in sublist
- Python | Maximum Sum Sublist
- Python | Indexing a sublist
- Python | Shift sublist in list
- Python | Replace sublist with other in list
- Python | Find maximum value in each sublist
- Python | Split Sublist Strings
- Python | Remove sublists that are present in another sublist
- Python | Convert nested sublist into tuples
- Python | Find the sublist with maximum value in given nested list
- Python | Slicing list from Kth element to last element
- Python | Indices of Kth element value
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.