Covich
Covich

Reputation: 2814

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

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

Thanks !

Upvotes: 13

Views: 13673

Answers (5)

hardik gosai
hardik gosai

Reputation: 398

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.

Upvotes: 0

Ashwath Iyer
Ashwath Iyer

Reputation: 1

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

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239453

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']

Upvotes: 14

Nishant Nawarkhede
Nishant Nawarkhede

Reputation: 8400

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']

Upvotes: 1

perreal
perreal

Reputation: 97938

An alternative with map:

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

or:

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

Upvotes: 3

Related Questions