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

1 Answer

0 votes
by (25.5k points)

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]
 

...