Lists are mutable, ordered sequences: indexing and slicing, + and *, the list methods and what they return, nested lists, copying, and the standard list programs.
| L = [10, 20, 30, 40] | L[1] = 20, L[-1] = 40, L[1:3] = [20, 30], L[::-1] = [40, 30, 20, 10] |
| Operators | [1, 2] + [3] = [1, 2, 3]; [0] * 3 = [0, 0, 0]; 3 in [1, 2, 3] is True |
| Methods | L = [5, 2, 8] L.append(1) # [5, 2, 8, 1] L.insert(0, 7) # [7, 5, 2, 8, 1] print(L.pop()) # 1 L.sort() # [2, 5, 7, 8] |
| append or extend | L.append([3, 4]) adds one item, a list; L.extend([3, 4]) adds 3 and then 4 |
| Functions | len(L), sum(L), max(L), min(L); L.count(x); L.index(x) gives the first position |
| Mean of a list | sum(L) / len(L) is a float: [4, 5, 9] gives 6.0 |
| Copy or not | M = L; M.append(9) changes L too; with M = L[:] it does not |
What does this program print?
L = [47, 9, 35, 15, 31, 38, 58, 39]
for i in range(0, len(L) - 1, 2):
L[i], L[i + 1] = L[i + 1], L[i]
print(L)
Working: items at even and odd positions swap in pairs; a last odd item stays
Answer: [9, 47, 15, 35, 38, 31, 39, 58]