Creating a list
A list is an ordered collection of items in [ ], separated by commas.
marks = [72, 85, 90]
mix = ["Ravi", 16, 7.5, True] # different types allowed
empty = []
nested = [1, [2, 3]] # a list inside a list
L = list("abc") # ["a", "b", "c"]
nums = list(range(1, 6)) # [1, 2, 3, 4, 5]You can also build one from input: L = eval(input()) or by appending in a loop.
Indexing and slicing
Each item has an index: 0, 1, 2… from the left, and −1, −2… from the right.
L[i] gives one item. A wrong index gives IndexError.
Slicing L[start:stop:step] gives a new list from start up to stop − 1. L[:2] = first two, L[2:] = from index 2 on, L[::-1] = reversed copy.
Traversing a list
Visiting each item once is called traversal.
for x in L: # by item
print(x)
for i in range(len(L)): # by index
print(i, L[i])Use the index form when you need the position or want to change items.
Changing a list and list operators
Lists are mutable: L[2] = 35 changes an item; L[0:2] = [1, 1] changes a slice; del L[1] deletes an item.
+joins:[1, 2] + [3]→ [1, 2, 3]*repeats:[0] * 3→ [0, 0, 0]in/not inchecks membership==,<compare item by item
Built-in functions for lists
len(L): number of itemsmax(L),min(L): largest, smallestsum(L): total of numberssorted(L): returns a NEW sorted list, L is unchangedlist(x): makes a list from a string, tuple or range
List methods
append(x): add one item at the endextend(list2): add every item of another list at the endinsert(i, x): put x at index iremove(x): delete the first x (ValueError if missing)pop(i): delete and return item at i (default last)clear(): empty the listindex(x): position of first xcount(x): how many times x appearssort(): sort in place (reverse=Truefor descending)reverse(): reverse in placecopy(): a new copy
Most methods change the list and return None. So L = L.sort() makes L None!
Try it: class marks list
Write the marks of 5 friends in a list. In Python: print the highest, lowest and average (sum(L)/len(L)). Append a new friend's marks, sort the list, then remove the lowest with L.pop(0). Predict each result first, then check with step 6 of the 3D.
Key formulas and definitions
- L[i], L[-i]; slice L[start:stop:step] (stop not included)
- len, max, min, sum, sorted, list
- append, extend, insert, remove, pop, clear, index, count, sort, reverse, copy
- average = sum(L) / len(L)
Worked examples
1. L = [5, 8, 2, 9]. Give L[1], L[-1] and L[1:3].
L[1] = 8, L[-1] = 9, L[1:3] = [8, 2].
2. L = [1, 2]. Compare L.append([3, 4]) and L.extend([3, 4]).
append adds the whole list as ONE item: [1, 2, [3, 4]] (length 3). extend adds each item: [1, 2, 3, 4] (length 4).
3. L = [3, 1, 4, 1, 5]. Find L.count(1), L.index(4) and sorted(L).
count(1) = 2, index(4) = 2, sorted(L) = [1, 1, 3, 4, 5] (L itself unchanged).
4. Write a program to find the average of marks [72, 85, 90, 65].
L = [72, 85, 90, 65] print(sum(L) / len(L)) → 312 / 4 = 78.0
5. Count how many even numbers are in L = [4, 7, 10, 3, 8].
c = 0 for x in L: if x % 2 == 0: c += 1 print(c) → 3 (4, 10, 8).
6. L = [10, 20, 30, 40]. What is L after: L.pop(1); L.insert(0, 5); L.remove(40)?
pop(1) removes 20 → [10, 30, 40]; insert(0, 5) → [5, 10, 30, 40]; remove(40) → [5, 10, 30].
Common mistakes
- Thinking the first index is 1. It is 0.
- Writing L = L.sort(); sort() returns None.
- Mixing pop (by position) and remove (by value).
- Using append to add many items; use extend.