AmbifulWorksheets
Cheat sheet
CBSE · Class 11 · Computer Science

Lists

Lists are mutable, ordered sequences: indexing and slicing, + and *, the list methods and what they return, nested lists, copying, and the standard list programs.

Key ideas

Remember

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
MethodsL = [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 extendL.append([3, 4]) adds one item, a list; L.extend([3, 4]) adds 3 and then 4
Functionslen(L), sum(L), max(L), min(L); L.count(x); L.index(x) gives the first position
Mean of a listsum(L) / len(L) is a float: [4, 5, 9] gives 6.0
Copy or notM = L; M.append(9) changes L too; with M = L[:] it does not

Watch out

Worked example

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]