Skip to content Skip to sidebar Skip to footer

Python - Get The Last Element Of Each List In A List Of Lists

My question is quite simple, I have a list of lists : my_list = [['a1','b1'],['a2','b2'],['a3','b3','c3'],['a4','b4','c4','d4','e4']] How can I get easily the the last element of

Solution 1:

You can get the last element of each element with the index -1 and just do it for all the sub lists.

print [item[-1] for item in my_list]
# ['b1', 'b2', 'c3', 'e4']

If you are looking for idiomatic way, then you can do

import operator
get_last_item = operator.itemgetter(-1)
print map(get_last_item, my_list)
# ['b1', 'b2', 'c3', 'e4']
print [get_last_item(sub_list) for sub_list in my_list]
# ['b1', 'b2', 'c3', 'e4']

If you are using Python 3.x, then you can do this also

print([last for *_, last in my_list])
# ['b1', 'b2', 'c3', 'e4']

Solution 2:

An alternative with map:

last_items = map(lambda x: x[-1], my_list)

or:

from operator import itemgetter
print map(itemgetter(-1), my_list)

Solution 3:

You can try ,

Here is demo.

>>> [i.pop() for i in my_list]
['b1', 'b2', 'c3', 'e4']

OR

>>> my_list = [['a1','b1'],['a2','b2'],['a3','b3','c3'],['a4','b4','c4','d4','e4']]
>>> [i[-1] for i in my_list]
['b1', 'b2', 'c3', 'e4']

Solution 4:

You can try:

my_list = [['a1','b1'],['a2','b2'],['a3','b3','c3'],['a4','b4','c4','d4','e4']]
print(my_list)

for each_list in my_list:
    last_element = each_list[-1]
    print(last_element)

Code tested successfully to arrive at the expected result - In the Attachment


Solution 5:

See the below answer,

my_list = [['a1','b1'],['a2','b2'],['a3','b3','c3'],['a4','b4','c4','d4','e4']]

new_list = []
for sub_list in my_list:
    new_list.append(sub_list[-1])

print(new_list) # o/p: [ 'b1' , 'b2' , 'c3' , 'e4' ]

I hope it helps you to find the answer.


Post a Comment for "Python - Get The Last Element Of Each List In A List Of Lists"