ducttape101
ducttape101

Reputation: 51

How to extract the last sub-list from a list of lists?

If I have a list of lists, how can I remove every element from each list, except for the last element? (Keeping only the last element from each list and deleting all other elements before it)

If my list of lists looks like this:

lst = [['Hello', 'World'], ['Hello', 'E', 'Planet'], ['Planet', 'World', 'Earth']]

I want my outputted list to look like this:

lst_new = [['World'], ['Planet'], ['Earth']]

So far, my code looks like this, but the problem I'm facing is that it is eliminating the last list entirely from the list of lists:

lst_new = [x for x in lst if x != lst.remove(lst[len(lst)-1])]
print(lst_new)
#[['Hello', 'World'], ['Hello', 'E', 'Planet']]

Where am I going wrong? Would appreciate any help - thanks!

Upvotes: 0

Views: 179

Answers (2)

Djaouad
Djaouad

Reputation: 22794

Just use simple indexing:

>>> lst_new = [ [x[-1]] for x in lst ]
>>> lst_new
[['World'], ['Planet'], ['Earth']]

Upvotes: 3

j1-lee
j1-lee

Reputation: 13939

You can use slicing:

lst = [['Hello', 'World'], ['Hello', 'E', 'Planet'], ['Planet', 'World', 'Earth']]

lst_new = [sublst[-1:] for sublst in lst]
print(lst_new) # [['World'], ['Planet'], ['Earth']]

Upvotes: 2

Related Questions