Visiting every item
Loop over a list and count the items that pass a test. About 8 minutes.
For each item
A for loop walks along a list in the same way it walks along a string. On every pass, a box takes the next item, from the first to the last. You don't need to know how long the list is.
Say a teacher has a list of test marks and wants to know how many students scored above a pass mark. Make a counter that starts at zero, loop over the marks, and add one whenever a mark is above the pass mark.
count = 0
for x in nums:
if x > limit:
count = count + 1- x
- 4
- count
- 0
4 is not above 5. The count is 0.
By value, or by position
There are two ways to loop over a list. The first gives you each value directly, which is the simplest. You use it whenever you only care about the values.
The second gives you each position, from 0 to the length minus 1, and you look up the value yourself. Use it when you need to know where you are, for example to compare an item with the one before it, as you did with letters. Choose the simplest one that does the job.
for i in range(len(nums)):
x = nums[i] # position i, value xnums is [3, 8, 1, 9] and limit is 5. How many items are above the limit?
- A2
- B1
- C4
Show the answer
2. 8 and 9 are above 5.
Count above the limit
Return how many numbers in the list are strictly bigger than limit.
nums = [4, 9, 2, 7, 5], limit = 5 → 2
0 ≤ length of nums ≤ 100,000 · −1,000,000 ≤ nums[i], limit ≤ 1,000,000