7. Data Structures: Arrays & Lists

Holding many values together

A single variable holds one value. But programs constantly deal with collections: all the scores in a class, every item in a cart, each line of a file. An array (often called a list) stores many values in one ordered container under a single name, so you can treat the whole group as a unit and reach any member when you need it.

90 85 72 95 60 0 1 2 3 4 scores — index below each cell

Indexing starts at zero

Each slot has a position number called its index. The crucial rule, shared by most languages, is that indexing starts at 0: the first item is at index 0, the second at index 1, and the last is at index length − 1. This "zero-based" counting feels odd at first and is the source of countless beginner bugs, so burn it in now.

scores = [90, 85, 72, 95, 60]
print(scores[0])    # 90  (first)
print(scores[4])    # 60  (fifth and last)
print(len(scores))  # 5   (how many items)
# scores[5]  -> ERROR: out of range (there is no index 5)

Iterating over a list

The natural partner of a list is a loop. A for loop can visit every element in turn, which is how you sum, search, filter or transform a collection.

scores = [90, 85, 72, 95, 60]
total = 0
for s in scores:
    total = total + s
print("Average:", total / len(scores))   # Average: 80.4

Common operations

OperationWhat it doesExample
AccessRead the item at an indexscores[2] → 72
UpdateReplace an itemscores[2] = 75
AppendAdd to the endscores.append(88)
RemoveDelete an itemscores.remove(60)
LengthCount the itemslen(scores) → 5
ContainsTest membership85 in scores → True

Maps / dictionaries (a quick look)

Lists find things by numeric position. Sometimes you want to find things by a meaningful key instead — a phone book looks people up by name, not by row number. For that there is the map (also called a dictionary, hash or associative array), which stores key → value pairs.

ages = {"Ada": 36, "Grace": 85}
print(ages["Ada"])        # 36 — look up by key, not index
ages["Linus"] = 54        # add a new pair

Key idea: arrays/lists group ordered values under one name and are accessed by zero-based index; loop over them to process every element, and reach for a map when a named key fits better than a position.