+4 votes
in Programming Languages by (77.2k points)
How can I delete the last element of a list in a Pythonic way?

1 Answer

+2 votes
by (354k points)
selected by
 
Best answer

There are several Pythonic ways to delete the last element of a list. You can try one of the followings:

Using 'del':

>>> aa=[11,23,34,56,54,32,21]
>>> del aa[-1]
>>> aa
[11, 23, 34, 56, 54, 32]

Using pop():

>>> aa=[11,23,34,56,54,32,21]
>>> aa.pop(len(aa)-1)
21
>>> aa
[11, 23, 34, 56, 54, 32]

Using the index:

>>> aa=[11,23,34,56,54,32,21]
>>> aa=aa[:-1]
>>> aa
[11, 23, 34, 56, 54, 32]
 


...