Menu

1D Arrays

Filling and printing arrays

To fill an array from user input, read a value inside a loop and assign it to the next index of the array. The loop variable acts as the index, so each pass stores its value in a different element.

heights = [0, 0, 0, 0]
for i in range(0, len(heights)):
    heights[i] = int(input("Height in cm: "))

for i in range(0, len(heights)):
    print("Sunflower", i + 1, "is", heights[i], "cm tall")

Output when the user types 34, 41, 29, 46:

Height in cm: 34
Height in cm: 41
Height in cm: 29
Height in cm: 46
Sunflower 1 is 34 cm tall
Sunflower 2 is 41 cm tall
Sunflower 3 is 29 cm tall
Sunflower 4 is 46 cm tall

The array is created holding four zeros — [0, 0, 0, 0] — and the loop then replaces each one with a typed value. On the first pass i is 0, so the first height goes into heights[0]; on the second pass i is 1, so the next height goes into heights[1], and so on. The loop runs once for every element, so each index is filled exactly once.

Printing every element

To print every element, loop over the indexes and output the element at each one. The second loop does this with print("Sunflower", i + 1, "is", heights[i], "cm tall"). Because i changes on each pass, a different element is read each time. The number printed is i + 1, so the element at index 0 is shown as sunflower 1 — the position, not the index.

Using len(heights) as the end of the loop means the loop always matches the array: the last index is len(heights) - 1, and range(0, len(heights)) stops there without going past the end.

Why use an array?

Without an array you would need a separate variable to hold each value, plus its own input line and its own print line for every one — four heights would mean four of each. Related values would be scattered across many names, and adding a fifth sunflower would mean editing lots of lines. An array keeps the values together under one name, and one loop can process all of them: the loop variable supplies the index, so the same short code fills or prints every element.

The array's size is fixed when it is created, so the number of elements does not change while the program runs; using len() keeps the loops in step with whichever size you chose.

Practise this