Lists
Lists: ordered and changeable
nums = [4, 2, 8] can hold any types, grow and shrink, and be indexed and sliced like strings.
Common operations
| Code | Effect |
|---|---|
lst.append(x) | add to the end |
lst.insert(i, x) | add at position i |
lst.extend(other) | add many items |
lst.remove(x) | remove first x (error if missing) |
lst.pop() / lst.pop(i) | remove and return the last item / item i |
lst.sort() | sort in place, returns None |
sorted(lst) | returns a new sorted list |
len(lst), min, max, sum | quick stats |
List comprehensions
A compact way to build lists:
[expression for item in iterable if condition]
⚠️ Common traps
nums = nums.sort()setsnumstoNone. Usenums.sort()alone, ornums = sorted(nums).b = adoes not copy a list: both names share it. Useb = a.copy().[[0] * 3] * 3creates 3 references to the same row. Use[[0] * 3 for _ in range(3)].
▶️ Runs in the app.
Example
nums = [4, 2, 8, 1]
nums.append(10)
nums.sort()
print(nums) # [1, 2, 4, 8, 10]
print(sorted(nums, reverse=True)) # [10, 8, 4, 2, 1]
squares_of_evens = [n ** 2 for n in nums if n % 2 == 0]
print(squares_of_evens) # [4, 16, 64, 100]
a = [1, 2, 3]
b = a # same list!
c = a.copy() # real copy
a.append(4)
print(b, c) # [1, 2, 3, 4] [1, 2, 3]
grid = [[0] * 3 for _ in range(3)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]