Lists and tuples hold many ordered values under one name; slicing pulls out ranges, and aliasing is the bug to watch for.
Lists vs tuples
- List
[ ]: ordered and mutable (change, add, remove). Use when it grows, shrinks, or reorders. - Tuple
( ): ordered and immutable. Use for fixed groups where position has meaning ((x, y)); can be a dict key. - Both support indexing, negative indexing,
len, slicing,for,in. - One-item tuple needs a trailing comma:
(5,)is a tuple,(5)is an int.
Indexing and access
- Index starts at
0; first isx[0], last isx[-1]orx[len(x)-1]. - Out-of-range index raises
IndexError;x[len(x)]is always invalid. - Negative indexing counts from the end:
-1last,-2second-to-last. - Nested:
grid[1][0]reads row 1, then its item 0. - Unpacking:
x, y = point(names must match item count). Swap witha, b = b, a.
Operation costs (n = list length)
x[i]index,len(x),x.pop()(from end): O(1)x.append(v): amortized O(1)x.insert(i, v),x.remove(v),v in x, fullforpass: O(n)- Slice of k items: O(k) time and space (builds a new list).
removedeletes only the first match and raisesValueErrorif absent.
Slicing: x[start:stop:step]
startincluded,stopexcluded,stepdefault 1.x[1:3]gives indices 1 and 2.- Omit
start= from beginning; omitstop= through end;x[:]= full copy. x[::2]every other item;x[::-1]reverses.- Out-of-range
stopis forgiving: it just stops at the end.
nums = [10, 20, 30, 40, 50]
index 0 1 2 3 4
[10, 20, 30, 40, 50]
nums[1:3] -> [20, 30] (1 in, 3 out)
Aliasing gotcha
b = acopies the reference, not the list. Both names point at one list, so a change through one shows in the other.- Real (shallow) copy:
b = list(a)orb = a[:], O(n). - Shallow copy still shares inner lists; use
copy.deepcopyfor fully independent nested structures.