Skip to content
List Basics
step 1/8

Reading — step 1 of 8

Learn

~3 min readLists and Tuples

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

python

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:

python

Unlike strings, you CAN modify a list in place:

python

Adding and removing elements

python
  • append(x) — add to end. Most common.
  • insert(i, x) — add at position i.
  • remove(x) — remove first matching VALUE (raises ValueError if not present).
  • pop() / pop(i) — remove + return the last (or specified) element.
  • clear() — empty the list completely.

len() — how many items

python

Iterating over a list

python

Searching

python

Sorting and reversing

Two important variants:

python

reverse() and reversed() follow the same in-place vs new-copy distinction.

Lists and references — the surprise

python

b = a doesn't copy the list — both names point to the same list in memory. To copy:

python

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 = a shares the list. Use a.copy(), a[:], or list(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, use collections.deque instead.
  • Confusing remove() and del: 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…