Python tip 24: modifying list using insert and slice
The insert()
list method helps to insert an object before the given index. Negative indexing is also supported.
>>> books = ['Sourdough', 'Sherlock Holmes', 'Cradle']
# same as: books.insert(-1, 'The Martian')
>>> books.insert(2, 'The Martian')
>>> books
['Sourdough', 'Sherlock Holmes', 'The Martian', 'Cradle']
# index >= list-length will append the object at the end
>>> books.insert(1000, 'Legends & Lattes')
>>> books
['Sourdough', 'Sherlock Holmes', 'The Martian', 'Cradle', 'Legends & Lattes']
You can use slicing notation to modify one or more list elements. The list will automatically shrink or expand as needed. Here are some examples:
>>> nums = [1, 4, 6, 22, 3, 5]
# modify a single element
>>> nums[0] = 100
>>> nums
[100, 4, 6, 22, 3, 5]
# modify the last three elements
>>> nums[-3:] = [-1, -2, -3]
>>> nums
[100, 4, 6, -1, -2, -3]
# elements at index 1, 2 and 3 are replaced with a single object
>>> nums[1:4] = [2000]
>>> nums
[100, 2000, -2, -3]
# element at index 1 is replaced with multiple elements
>>> nums[1:2] = [3.14, 4.13, 6.78]
>>> nums
[100, 3.14, 4.13, 6.78, -2, -3]
RHS must be an iterable when you use slicing notation with :
, even when LHS refers to a single element. For example, nums[1:2] = 100
is not valid.
Video demo:
See also my 100 Page Python Intro ebook.