1D Arrays
An array is a fixed-length (or static) structure: you decide how many elements it will hold when you set it up, and that number stays the same for the whole run of the program. Because the size never changes, the program always knows how many elements it has to work with.
A fixed length does not mean the contents are frozen. Each element can be given a new value while the program runs by assigning to its index, so an array of ticket prices could have one price corrected without the array changing size.
Writing the values inside square brackets creates the array at full size straight away, so every element is ready to be read or replaced by index. For example, prices = [15, 22, 9, 30, 18, 12] creates an array of six elements, one for each ticket type; prices[4] = 20 replaces the fifth element, but the array still holds six elements.
# Six plants in a row, created with each plant's height in cm
plant_heights = [12, 25, 18, 30, 22, 9]
plant_heights[2] = 21 # one height is corrected, the length does not change
print(plant_heights)
print(len(plant_heights))Output:
[12, 25, 21, 30, 22, 9]
6You can also start with an empty array and use append to add one element to the end each time. If the array needs six elements, append six times; once the last element is added the array is complete, and from then on you read and change elements by index instead of appending again. Python will let you keep appending to a list, so it is up to you to fix the size: work out how many elements are needed, add exactly that many and treat the array as full.
# A fixed six-element array built by appending one element at a time
visitors = []
for day in range(1, 7):
visitors.append(day * 40)
visitors[5] = 260 # one value changes, the length stays at six
print(visitors)
print(len(visitors))Output:
[40, 80, 120, 160, 200, 260]
6