Lists in Python
Lists are ordered, mutable sequences that can hold any objects.
Creating lists
Literal, constructor, and repetition forms. Beware repetition with mutable items.
empty = []
nums = [1, 2, 3]
words = list(("a", "b"))
zeros = [0] * 5
nested = [[1, 2], [3, 4]]
Pitfall:
bad = [[0]*3]*2 # duplicates references → mutating one row affects both
Indexing and slicing
Zero‑based indexing; negative indices count from the end. Slices return new lists.
nums = [10, 20, 30, 40, 50]
nums[0], nums[-1]
nums[1:4] # [20, 30, 40]
nums[:3] # [10, 20, 30]
nums[::2] # [10, 30, 50]
Slicing assignment can grow/shrink lists.
nums[1:3] = [99, 100, 101]
Adding and removing
Append, extend, insert, and pop/remove/clear.
xs = [1, 2]
xs.append(3)
xs.extend([4, 5])
xs.insert(1, 9)
xs.pop() # removes and returns last
xs.remove(9) # remove first matching value (ValueError if missing)
xs.clear() # remove all
Modify in place vs new list
Methods like sort mutate; functions like sorted return new lists. key and reverse control ordering.
xs = ["aa", "b", "ccc"]
xs.sort(key=len) # in place
ys = sorted(xs, reverse=True)
Comprehensions and map/filter
Concise transforms with optional filters; prefer comprehensions for clarity.
squares = [n*n for n in range(5)]
evens = [n for n in range(10) if n % 2 == 0]
upper = [s.upper() for s in ["a", "b"]]
Copying lists
Shallow vs deep copy; slicing is a shallow copy.
import copy
shallow = xs.copy() # or xs[:]
deep = copy.deepcopy(nested)
Membership and search
3 in nums
nums.index(20) # ValueError if not present
nums.count(10)
Performance notes
- List append is amortized O(1); insert/pop at front are O(n)
- Prefer
dequefromcollectionsfor efficient queue/stack at both ends
Summary
- Lists are dynamic and mutable; choose in‑place or new‑list operations intentionally
- Prefer comprehensions and
sortedfor clarity; deep copy nested structures when duplicating