Home > database >  How to eliminate all elements from a Python list of lists except for the last one?
How to eliminate all elements from a Python list of lists except for the last one?

Time:07-11

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!

CodePudding user response:

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

CodePudding user response:

Just use simple indexing:

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