Reading — step 1 of 8
Learn
Imagine a row of lockers in a hallway. Each locker has a number painted on it — 0, 1, 2, 3 — and each locker holds exactly one thing. You can open any locker by its number, swap what's inside, add a new one at the end, or rip one out of the middle. That's a Python list: an ordered, numbered, mutable sequence of values.
Creating lists
Unlike strings, lists can hold values of any type — even mixed types in the same list. (In practice, keep types consistent within a list — it makes the code more predictable.)
Accessing and updating elements
Lists use the same zero-based indexing as strings, including negative indices and slicing:
Unlike strings, you CAN modify a list in place:
Adding and removing elements
append(x)— add to end. Most common.insert(i, x)— add at position i.remove(x)— remove first matching VALUE (raisesValueErrorif not present).pop()/pop(i)— remove + return the last (or specified) element.clear()— empty the list completely.
len() — how many items
Iterating over a list
Searching
Sorting and reversing
Two important variants:
reverse() and reversed() follow the same in-place vs new-copy distinction.
Lists and references — the surprise
b = a doesn't copy the list — both names point to the same list in memory. To copy:
This bites every Python beginner at least once. Lists are passed by reference everywhere — function arguments, dictionary values, anywhere.
Common mistakes
- Using
=to copy:b = ashares the list. Usea.copy(),a[:], orlist(a)to make an independent copy. - Modifying a list while iterating:
for x in items: items.remove(x)skips elements. Iterate over a copy:for x in items[:]:. pop()from the front:pop(0)is O(n) because every other element shifts. For queue-like patterns, usecollections.dequeinstead.- Confusing
remove()anddel:remove(x)removes by VALUE.del list[i]removes by INDEX.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…