Python | Get last element of each sublist
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]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course