Python tip 16: delete list elements using index or slice
The pop()
method removes the last element of a list
by default. You can pass an index to delete that specific item and the list will be automatically re-arranged. Return value is the element being deleted.
>>> primes = [2, 3, 5, 7, 11]
>>> primes.pop()
11
>>> primes
[2, 3, 5, 7]
>>> student = ['learnbyexample', 2022, ['Linux', 'Vim', 'Python']]
>>> student.pop(1)
2022
>>> student[-1].pop(1)
'Vim'
>>> student
['learnbyexample', ['Linux', 'Python']]
To remove multiple elements using slicing notation, use the del
statement. Unlike the pop()
method, you won't get the elements being deleted as the return value.
>>> books = ['cradle', 'mistborn', 'legends & lattes', 'sourdough']
>>> del books[-1]
>>> books
['cradle', 'mistborn', 'legends & lattes']
>>> del books[:2]
>>> books
['legends & lattes']
>>> student = ['learnbyexample', 2022, ['Linux', 'Vim', 'Python']]
>>> del student[-1][1]
>>> student
['learnbyexample', 2022, ['Linux', 'Python']]
Video demo:
See also my 100 Page Python Intro ebook.