As you'll remember, list elements are indexed, meaning they have sequence numbers. The first element has an index of 0
, and the last one has len(list) - 1
index.
The function len()
returns the length of a list, but it works with different types, such as strings and tuples.
List items can be obtained and replaced by assigning them to their index. If we specify a negative index, we take elements from the end.
The last element of the list will have a negative index, -1
. Sadly, there's no way to use -0
. Here are a couple of examples of using indexes with a list:
l = [0] * 3
l[0], l[1] = 10, 32
l[-1] = l[0] + l[1]
print(l) # => [10, 32, 42]
Note that we created the list by cloning zeros. It's safe to do so because Python numbers are immutable. However, we do all list modifications through assignment, so we wouldn't get anything unexpected even if we used mutable objects.
The pop
and insert
methods
So, we know how to get and replace elements one by one. It would also be nice to be able to delete old items and insert new ones in the middle of the list. The pop
and insert
methods are responsible for this.
The pop
removes an element by index. If we don't specify an index, Python will delete the last element. In doing so, the pop
returns the deleted value:
l = [1, 2, 3]
l.pop() # 3
print(l) # => [1, 2]
l.pop(0) # 1
print(l) # => [2]
And here's an example of the insert
being used:
l = [1, 2, 3]
l.insert(1, 100)
print(l) # => [1, 100, 2, 3]
l.insert(-1, 200)
print(l) # => [1, 100, 2, 200, 3]
The insert
method always inserts a new item before the item with the specified index relative to the beginning of the list. It doesn't matter whether we counted the index from the beginning or the end. And insert(-1, ..)
inserts an element before the last one.