Was it helpful?

Question


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 last 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 -1 in them. A for loop is used for this purpose as shown below.

Example

 Live Demo

Alist = [['Mon', 1], ['Tue', 'Wed', "Fri"], [12,3,7]]
print("Given List:\n",Alist)
print("Lastst Items from sublists:\n")
for item in Alist:
   print((item[-1]))

Output

Running the above code gives us the following result −

Given List:
[['Mon', 1], ['Tue', 'Wed', 'Fri'], [12, 3, 7]]
First Items from sublists:
1
Fri
7

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 reversed list to 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

 Live Demo

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(*map(reversed,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:
[1, 'Fri', 7]

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

 Live Demo

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(-1), 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:
[1, 'Fri', 7]
raja
Published on 09-Sep-2020 12:33:01

Was it helpful?
Not affiliated with Tutorialspoint
scroll top