List patterns
Part of the free LogicWiz Python course, Module 5: Lists and tuples. The examples and practice run in the app.
The CBSE practical examiner says: "Find the largest marks. Don't use max()." Half the class starts with big = 0, and the examiner tries a list of negative temperatures.
You'll learn to
- Find the max, min, sum and average with a loop
- Search a list item by item (linear search)
- Count how often values appear, and swap items by position
Learn
A pattern is a recipe
Most list programs follow one recipe:
- Start a result variable.
- Loop over the list.
- Update the result when an item matters.
The start value is where people slip. For a sum, start at 0. For a max or min, start at the first item lst[0], not at 0, because the list might be all negative (or all above 100).
Max and min by hand
temps = [31, 28, 35, 30]
high = temps[0]
low = temps[0]
for t in temps:
if t > high:
high = t
if t < low:
low = t
print("High:", high, "Low:", low)
Step through and watch high and low change only when a bigger (or smaller) value turns up.
Sum, average, count above average
marks = [78, 92, 65, 88, 70]
total = 0
for m in marks:
total += m
avg = total / len(marks)
print("Total:", total, "Average:", avg)
above = 0
for m in marks:
if m > avg:
above += 1
print("Above average:", above)
Linear search
def search(lst, target):
for i in range(len(lst)):
if lst[i] == target:
return i
return -1
rolls = [12, 7, 31, 5, 18]
print(search(rolls, 31))
print(search(rolls, 40))
Check items one by one. Return the index as soon as you find it. Only after the whole loop is it safe to say "not found" (-1).
Frequency of each item
orders = ["chai", "samosa", "chai", "maggi", "chai", "samosa"]
seen = []
for item in orders:
if item not in seen:
seen.append(item)
for item in seen:
count = 0
for x in orders:
if x == item:
count += 1
print(item, count)
First collect each item once (seen), then count each. In Module 6 a dictionary does this in one pass.
Swapping positions
a = [10, 20, 30, 40, 50]
a[0], a[4] = a[4], a[0]
print(a)
b = [1, 2, 3, 4, 5, 6]
for i in range(0, len(b) - 1, 2):
b[i], b[i + 1] = b[i + 1], b[i]
print(b)
x, y = y, x swaps in one line. The loop jumps by 2 and swaps each even position with the odd one after it. len(b) - 1 stops it safely when the length is odd.
Two classic slips:
big = 0before a max loop gives0for[-5, -2, -9]. Start withbig = lst[0].- In a search,
else: return -1inside the loop gives up after checking only the first item.
These are straight from the CBSE Class 11 practical list: find the largest/smallest number in a list, search for an element (linear search), count the frequency of elements, and swap elements at even locations with elements at odd locations. Write them as functions and practise them without max, min, index or count.
In one line
Start a max/min at lst[0], a sum at 0; return -1 only after the whole search loop; swap with a[i], a[j] = a[j], a[i].