Modifying Lists
You can add new items to the end of the list by using its append()
method (list
is an object
!)
>>> numbers = [] # this creates a new empty list
>>> numbers.append(6)
>>> print(numbers)
>>> numbers.append(2)
>>> print(numbers)
You can also add multiple items to a list directly with the extend()
method.
>>> numbers = [1, 2, 3]
>>> numbers.extend([4, 5, 6])
>>> print(numbers)
You can delete items from a list with the del
operator.
>>> numbers = [1, 2, 3]
>>> print(numbers)
>>> del numbers[1]
>>> print(numbers)
The official documentation provides many more methods for the list
object, for example .extend()
, .insert()
, .pop()
, .remove()
, .reverse()
, .index()
, and .sort()
. Please explore these at your own leisure.
List operators
The operators +
and *
have been overloaded for list
s.
So, you can concatenate two lists by ‘adding’ the list together. Try this and see what happens.
>>> print([1, 2] + [3, 4, 5])
You can also replicate elements in a list by ‘mutiplying’ it with a scalar. Try this and see what happens.
>>> print([1, 2] * 3)
The membership operator (in
) is also useful for checking whether a particular object is in a list. This returns a bool
(True
or False
).
>>> print(3 in [1,2,3,4])
>>> print(3 not in [1,2,3,4])
>>> print("snake" in ["I", "am", "not", "afraid", "of", "Python"])