Totals, means, largest and smallest values and linear search on a list, parallel lists, and working along the rows and columns of a 2D list.
What you will learn
- Total a list and find its mean
- Find the largest or smallest item without max or min
- Write a linear search that returns an index or -1
- Loop through the rows and columns of a 2D list
Working through a list
Most list tasks are one loop with a variable that remembers something: a total, a count, or the best value so far.
The largest value, without max()
function highest(values)
best = values[0]
for i = 1 to values.length - 1
if values[i] > best then
best = values[i]
endif
next i
return best
endfunction
print(highest([-4, -9, -2, -7]))SUBROUTINE highest(values)
best ← values[0]
FOR i ← 1 TO LEN(values) - 1
IF values[i] > best THEN
best ← values[i]
ENDIF
ENDFOR
RETURN best
ENDSUBROUTINE
OUTPUT highest([-4, -9, -2, -7])def highest(values):
best = values[0]
for i in range(1, len(values)):
if values[i] > best:
best = values[i]
return best
print(highest([-4, -9, -2, -7]))This prints -2. Starting from the first item, not from 0, matters: if every value is negative, 0 is not in the list at all.
Some tasks build a new list. Start with an empty list, result = [], and add to the end of it with result.append(x). So a loop that appends each score over 50 from [42, 77, 51] gives [77, 51].
To find a mean (average), add up the values and divide by how many there are: the mean of 4, 9 and 5 is 18 / 3 = 6.0. In Python / always gives a real number, while // gives the whole-number part.
A linear search checks each item in turn and returns its index as soon as it matches. Only after the whole list has been checked does it return -1 for "not found".
- Decide what to remember: a total, a count, a best value or an index.
- Set it up before the loop.
- Loop through every index (or every item).
- Update it inside the loop.
- Return it after the loop, unless you have found what you were searching for.
The rest of this lesson and its 9 practice questions are locked.
In this lesson
- Working through a list
- Parallel lists
- 2D lists
- Try it: A running total
9 practice questions, marked as you go; about 30 minutes in all.
Key terms
Mean, Linear search, Parallel lists
In this unit: Writing code
Write real Python that runs against tests: functions, validation and logins, strings, lists and 2D lists, records, and completing and refining a program.