Python for C++ Programmers
Chapter 4: Sequence types
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)
[6]
>>> numbers.append(2)
>>> print(numbers)
[6, 2]
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)
[1, 2, 3, 4, 5, 6]
You can delete items from a list with the del
operator.
>>> numbers = [1, 2, 3]
>>> print(numbers)
[1, 2, 3]
>>> del numbers[1]
>>> print(numbers)
[1, 3]
The official documentation provides many more methods for the list
object, for example .insert()
, .pop()
, .remove()
, .reverse()
, .index()
, and .sort()
. Please explore these at your own leisure.