Guillaume
Guillaume

Reputation: 2918

Python - How to delete the last element in a list of lists?

I have a list of lists like this:

listadr = [[a, b], [1, 2]]

How to remove the last entry of the last list to have this result ?

result = [[a, b], [1]]

I have tried

for adr in listadr:
   for adr[1] in adr:
      del adr[-1]

But this code delete also 'b' ...

Upvotes: 1

Views: 3449

Answers (2)

thefourtheye
thefourtheye

Reputation: 239443

Delete only the last element's last element, like this

listadr = [['a', 'b'], [1, 2]]
del listadr[-1][-1]
print(listadr)
# [['a', 'b'], [1]]

listadr[-1] will get the last element of listadr and listadr[-1][-1] will get the last element of the last element of listadr and kill it with del.

Alternatively, you can do

listadr[-1] = listadr[-1][:-1]

This would be replacing the last element of listadr with the last element of listadr excluding its last element. listadr[-1][:-1] means get all the elements till the last element of the last element of listadr.

Upvotes: 9

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

There's no need to loop here, simply index the list using [-1][-1]:

>>> listadr = [['a', 'b'], [1, 2]]
>>> del listadr[-1][-1]
>>> listadr
[['a', 'b'], [1]]

If you want the item as well then use list.pop() on last sublist:

>>> listadr = [['a', 'b'], [1, 2]]
>>> listadr[-1].pop()
2
>>> listadr
[['a', 'b'], [1]]

Upvotes: 5

Related Questions