Until now each variable stored a single value. When you need to store many (10 marks, 1000 numbers), creating a variable for each one is not feasible. That is what arrays are for. In Python they are called lists (list).
Creating a list
numbers = [4, 8, 15, 16]
names = ["Ana", "Luis", "Eva"]
mixed = [1, "hello", 3.5, True] # types can be mixed
empty = []
print(numbers) # [4, 8, 15, 16]
print(len(numbers)) # 4
They are written between square brackets, with the elements separated by commas. len() returns how many elements there are.
Indexes
Just like in strings, each element has a position that starts at 0, and negative ones count from the end:
numbers = [4, 8, 15, 16]
print(numbers[0]) # 4
print(numbers[2]) # 15
print(numbers[-1]) # 16 (the last one)
print(numbers[4]) # IndexError: list index out of range
Slices
print(numbers[1:3]) # [8, 15]
print(numbers[:2]) # [4, 8]
print(numbers[::-1]) # [16, 15, 8, 4] (the list reversed)
A slice returns a new list; the original does not change. It is one of the ways to solve Reverse order array.
Lists are mutable
Unlike strings, you can change an element in place:
numbers[0] = 100
print(numbers) # [100, 8, 15, 16]
Checking whether a value is there: in
print(15 in numbers) # True
print(99 in numbers) # False
print(99 not in numbers)# True
Joining and repeating
print([1, 2] + [3]) # [1, 2, 3]
print([0] * 4) # [0, 0, 0, 0]
[0] * n is the usual way to create a list of n initial positions.