Lists and Indexing
One name for many values, kept in order. Indexing reaches in by position - and counting from zero is the part that catches everyone once.
A list is ordered, and starts at zero
Positions are counted from 0, so the third item is at index 2. A negative index counts back from the end.
Lists can change after you make them
Unlike a string, a list is mutable: you can replace an item, add to the end, or remove one, and the same list object changes.
How a list is laid out
len(x) - 1, or just x[-1].IndexError. That is Python refusing to guess, not a crash to be afraid of.append adds one item to the end. remove deletes the first match by value, not by position.sorted(x) returns a new sorted list and leaves the original alone. x.sort() reorders it in place and returns nothing - a classic source of None surprises.Lists and Indexing: A Practical Guide
A row of boxes, numbered from zero.
Quick Context
A list holds several values in a fixed order under one name. You write it with square brackets and commas. The order you put things in is the order they stay in, which is what separates a list from the unordered collections you will meet later.
Why counting starts at zero
An index is best read as "how far from the start", not "which one". The first item is zero steps from the start, so it is at index 0. Once you read it that way, colours[2] being the third colour stops feeling like a trick.
Interactive Exploration Guide
- Run the first editor. Check that
colours[0]is red andcolours[2]is blue - the third one. - Ask for one too far. Add
print(colours[4])and run. Four items, so the last index is 3: Python raisesIndexErrorrather than inventing a value. - Run the second editor and watch the list change. The same list is printed three times and differs each time, because the methods modify it in place.
- Compare the last two lines.
sorted(stack)prints in order, but the followingprint(stack)shows the original untouched. Swap instack.sort()and the difference is obvious.
Key Takeaway
A list is an ordered, changeable row of values indexed from zero. Reading past the end raises IndexError instead of guessing, and the difference between a method that returns a new list and one that edits the original is worth learning early - it explains most beginner bugs involving None.