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 !
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']
An alternative with map
:
last_items = map(lambda x: x[-1], my_list)
or:
from operator import itemgetter
print map(itemgetter(-1), my_list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With