Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - get the last element of each list in a list of lists

Tags:

python

list

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 each list i.e. :

[ 'b1' , 'b2' , 'c3' , 'e4' ]

Thanks !

like image 999
Covich Avatar asked Apr 15 '14 08:04

Covich


2 Answers

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']
like image 88
thefourtheye Avatar answered Nov 02 '22 13:11

thefourtheye


An alternative with map:

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

or:

from operator import itemgetter
print map(itemgetter(-1), my_list)
like image 30
perreal Avatar answered Nov 02 '22 12:11

perreal