Indexing (x[0], d["key"])
Square brackets ask for one item: by position in a list or string, or by key in a dict.
Used in 129 lessons of the course, from 00.01.
Square brackets after a value, like x[0], ask for one item from that value.
In a list, tuple or string, you put a number: the position. Counting starts at 0, so x[0] is the first item and x[1] the second.
In a dict, you put a key: d["key"] returns the value stored under that key.
It is written this way because Python uses one shape for everything that holds things: what goes inside the brackets says which one you want.
The course uses it from lesson 00.01: where = GLOSSARY[key] looks in the GLOSSARY dict for the value of whatever key holds. If the key is missing, Python raises a KeyError.
colors = ["red", "green"]
print(colors[0])
Reach for it when: you need a single item and you know its position or its key.
Examples
Common mistake
colors = ["red", "green", "blue"] print(colors[3])
Why: The list has 3 items, at positions 0, 1 and 2. Position 3 does not exist.
How to write it: Use a position from 0 to len(list) - 1, such as colors[2], or colors[-1] for the last one.
Common mistake
GLOSSARY = {"list": "an ordered collection"}
print(GLOSSARY["tuple"])Why: The dict has no "tuple" key, and square brackets require it to exist.
How to write it: Check the key is spelled the same, or use GLOSSARY.get("tuple") if it may be missing.
