Home › Learn › Python › Lists

Iterating and enumerate

Lesson 17 of 40. Visit every item, with or without its position.

for item in items: gives you each value in turn; you rarely need an index. When you do need the position as well, for i, item in enumerate(items): gives both, counting from zero, or enumerate(items, start=1) to count from one.

Summing, counting, and collecting are the three loop shapes: an accumulator variable before the loop, updated inside, returned after. Python has sum(), min(), and max() built in for the common cases; writing the loop once teaches what they do.

for i, name in enumerate(["Ann", "Ben"], start=1):
    print(f"{i}. {name}")
# 1. Ann
# 2. Ben

Your task

Write total(prices) that adds up a list of numbers with a loop, and numbered(names) that returns a list of strings like "1. Ann", "2. Ben" using enumerate.

Hint 1

result = 0; for p in prices: result += p; return result

Hint 2

for i, name in enumerate(names, start=1): result.append(f"{i}. {name}")

Show the solution
def total(prices):
    result = 0
    for p in prices:
        result += p
    return result


def numbered(names):
    result = []
    for i, name in enumerate(names, start=1):
        result.append(f"{i}. {name}")
    return result

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.