Python 3D Academyবাংলা

Looping over a list

🌍 In real life. At the start of class, the teacher reads every name on the register, top to bottom, once each. At the end of term, they go down the marks column adding them up, or looking for the highest. Each job visits every item once, in order.

A for loop does exactly that with a list.

The idea in one sentence: for item in my_list: visits every item of the list in order, putting each one in the loop variable, so you can print it, add it up, or keep it.

Its words:

  • for item in my_list:: the same for loop you used with range() and strings
  • sum(), min(), max(): ready-made helpers that walk a list of numbers for you
  • filtering: building a new list that keeps only the items you want
  • .split(): cuts text into a list of words

Step by step, for the names below:

  1. name gets "Ana", and the block prints Hi Ana.
  2. name gets "Bo", then "Cy", and the block runs for each.
  3. No items are left, so the loop ends.
names = ["Ana", "Bo", "Cy"]
for name in names:
    print("Hi", name)

For lists of numbers, Python has ready-made helpers: sum() adds them all, and min() and max() find the smallest and the largest. The average is sum(...) / len(...).

scores = [7, 9, 4, 10]
print(sum(scores))
print(min(scores), max(scores))
print(sum(scores) / len(scores))

A loop can also build a new list from an old one, keeping only the items you want:

nums = [3, 8, 1, 6]
big = []
for n in nums:
    if n > 4:
        big.append(n)
print(big)

To read many numbers from one line, .split() cuts the text into a list of strings. Turn each one into a number with int():

words = input("Numbers: ").split()
nums = []
for w in words:
    nums.append(int(w))
print(nums, "add up to", sum(nums))

How Python does it, and what it costs. The loop variable holds the item itself, not its index, so you rarely need range(len(...)). Each lap handles one item, so a loop over n items does n laps, and so do sum(), min() and max(): each walks the whole list once. Filtering into a new list is also one pass, which is much cheaper than removing items from the old list one by one.

Mistakes and edge cases.

  • An empty list. sum([]) is 0, but max([]) gives ValueError: max() iterable argument is empty, and an average divides by len([]), which is 0.
  • Forgetting int() after split(). sum(["4", "7"]) gives TypeError: unsupported operand type(s) for +: 'int' and 'str'.
  • Changing the list you're looping over. Removing items inside the loop skips some. Build a new list instead.
  • Expecting an index. In for x in [10, 20]:, x is 10 and then 20, not 0 and 1.

Quiz

  1. What does this print?

    for x in [2, 4, 6]:
        print(x // 2)
  2. What does this print?

    print(sum([1, 2, 3]), max([4, 9, 2]))
  3. What does this print?

    nums = [5, 12, 7, 20]
    count = 0
    for n in nums:
        if n > 10:
            count += 1
    print(count)
  4. What does "3 7 1".split() give?

    • ['3', '7', '1'], a list of strings
    • [3, 7, 1], a list of numbers
    • 371
  5. Which line has a mistake?

    nums = [4, 6, 8]
    print(sum(nums) / len(num))

Coding tasks

  1. Here are some prices: prices = [12, 5, 8, 20]. Print the total of all the prices, then the most expensive price.

  2. Ask for whole numbers on one line, separated by spaces. Print how many of them are even.

  3. Ask for whole numbers on one line, separated by spaces. Print a list of running totals: each item is the sum of all the numbers up to that point. For 1 2 3 4 the answer is [1, 3, 6, 10].