Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

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.

for each item in the list: test it, and count it if it passes.
In code
count = 0
for x in nums:
    if x > limit:
        count = count + 1
How many marks are above 5?
4
0
9
1
2
2
7
3
5
4
x
x
4
count
0

4 is not above 5. The count is 0.

Move 1 of 5

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.

Only the values? Loop over the values. Need the position? Loop over positions.
In code
for i in range(len(nums)):
    x = nums[i]      # position i, value x