Python Lists
Data Types Focus
Python Lists
Lists are ordered, mutable collections. Master creation, slicing, methods, and copying behavior to avoid hidden bugs.
Creating lists
empty = []
numbers = [1, 2, 3]
mixed = [42, "python", True]
list_from_range = list(range(5))
Indexing and slicing
letters = ["a", "b", "c", "d"]
letters[0] # 'a'
letters[-1] # 'd'
letters[1:3] # ['b', 'c']
letters[::2] # ['a', 'c']
Slicing returns a new list. Mutating a slice modifies the original list.
List methods
| Method | Description |
|---|---|
| append(x) | Add single element to end |
| extend(iterable) | Add multiple elements |
| insert(i, x) | Insert at position (O(n)) |
| remove(x) | Remove first occurrence (ValueError if missing) |
| pop([i]) | Remove and return element |
| sort() | In-place sort (stable) |
| sorted(list) | Return new sorted list |
Copying lists
a = [1, 2]
b = a # Shares reference
c = a.copy() # Shallow copy
d = a[:] # Another shallow copy
- Use
copy.deepcopyfor nested lists. - When passing lists to functions, consider whether you want to mutate the original.
List comprehensions
squares = [n * n for n in range(10)]
even_ids = [user.id for user in users if user.active]
Readable, performant alternative to loops. For nested loops, use multiple for clauses.
Performance tips
- Append is amortized O(1); prefer it over repeated
+with new lists. - Use
collections.dequefor queue-like behavior. - Avoid large list-of-lists when NumPy arrays fit better (for numeric workloads).
Next up in your learning path
Frequently Asked Questions
Are lists dynamically sized?
Yes. Lists over-allocate memory to support fast append operations. You don't need to predefine size as you do in lower-level languages.
Why does `list * n` surprise me?
Multiplying a list replicates references. `[[0] * 3] * 4` creates four references to the same inner list. Use comprehensions to create independent lists.
Should I prefer `sorted()` or `.sort()`?
Use `sorted()` when you need a new list and to avoid mutating the original. Use `.sort()` for in-place updates when you don't need the previous ordering.