Given a list of lists, write a Python program to extract first element of each sublist in the given list of lists.
Examples:
Input : [[1, 2], [3, 4, 5], [6, 7, 8, 9]] Output : [1, 3, 6] Input : [['x', 'y', 'z'], ['m'], ['a', 'b'], ['u', 'v']] Output : ['x', 'm', 'a', 'u']
Approach #1 : List comprehension
# Python3 program to extract first and last # element of each sublist in a list of lists def Extract(lst): return [item[0] for item in lst] # Driver code lst = [[1, 2], [3, 4, 5], [6, 7, 8, 9]] print(Extract(lst)) |
[1, 3, 6]
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. Thus, all the first element will become the first tuple of the zipped list. Returning the 0th element will thus, solve the purpose.
# Python3 program to extract first and last # element of each sublist in a list of lists def Extract(lst): return list(list(zip(*lst))[0]) # Driver code lst = [[1, 2], [3, 4, 5], [6, 7, 8, 9]] print(Extract(lst)) |
[1, 3, 6]
Another method of using zip is given below:-
def Extract(lst): return list(next(zip(*lst))) |
Approach #3 : Using itemgetter()
# Python3 program to extract first and last # element of each sublist in a list of lists from operator import itemgetter def Extract(lst): return list( map(itemgetter(0), lst )) # Driver code lst = [[1, 2], [3, 4, 5], [6, 7, 8, 9]] print(Extract(lst)) |
[1, 3, 6]
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.
Recommended Posts:
- Python | Get last element of each sublist
- Python | Multiply each element in a sublist by its index
- Python | Find maximum value in each sublist
- Python | Sort a list according to the second element in sublist
- Python | Getting sublist element till N
- Python - Replace sublist from Initial element
- Python | Shift sublist in list
- Python | Maximum Sum Sublist
- Python | Indexing a sublist
- Python | Remove sublists that are present in another sublist
- Python | Find the sublist with maximum value in given nested list
- Python | Split Sublist Strings
- Python | Replace sublist with other in list
- Python | Convert nested sublist into tuples
- Python - Incremental Sublist Sum
- Python | Mean of consecutive Sublist
- Python - Sublist Maximum in custom sliced List
- Python - Check for Sublist in List
- Python - Count frequency of Sublist in given list
- Python IMDbPY – Get each episode name of each season of the series
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.

