A list in python can also contain lists inside it as elements. These nested lists are called sublists. In this article we will solve the challenge of retrieving only the first element of each sublist in a given list.
Using for loop
It is a very simple approach in which we loop through the sublists fetching the item at index 0 in them. A for loop is used for this purpose as shown below.
Example
Alist = [['Mon', 1], ['Tue', 'Wed', "Fri"], [12,3,7]] print("Given List:\n",Alist) print("First Items from sublists:\n") for item in Alist: print((item[0]))
Output
Running the above code gives us the following result −
Given List: [['Mon', 1], ['Tue', 'Wed', 'Fri'], [12, 3, 7]] First Items from sublists: Mon Tue 12
Using zip and *
The * allows us to unpack the sublists and give access to individual elements of the sublist. So in this case we will use * and access the element at index 0 from each element. Then we finally zip the result to get a list of the first element from the sublists.
Example
Alist = [['Mon', 1], ['Tue', 'Wed', "Fri"], [12,3,7]] print("Given List:\n",Alist) print("\n First Items from sublists:\n") print(list(list(zip(*Alist))[0]))
Output
Running the above code gives us the following result −
Given List: [['Mon', 1], ['Tue', 'Wed', 'Fri'], [12, 3, 7]] First Items from sublists: ['Mon', 'Tue', 12]
Using itemgetter
The itemgetter(i) constructs a callable that takes an iterable object like dictionary,list, tuple etc. as input, and fetches the i-th element out of it. So we can use this method to get the first items of the list using the map function as follows.
Example
from operator import itemgetter Alist = [['Mon', 1], ['Tue', 'Wed', "Fri"], [12,3,7]] print("Given List:\n",Alist) print("\n First Items from sublists:\n") print(list(map(itemgetter(0), Alist)))
Output
Running the above code gives us the following result −
Given List: [['Mon', 1], ['Tue', 'Wed', 'Fri'], [12, 3, 7]] First Items from sublists: ['Mon', 'Tue', 12]