← Intro to programming with Python

Looping over lists, and checking with in

Do something with every item, and ask "is it in there?"

Start this lesson

Lists and for loops are best friends. for item in my_list: runs the loop once for each item, giving you the item itself, so there is no need to fiddle with index numbers. The word in also works as a question: "milk" in fridge is True when the list contains "milk". These two tools together let you filter a list, building a new list that keeps only the items you want.

fridge = ["milk", "eggs", "spinach"]
for food in fridge:
    print("We have", food)
if "cheese" not in fridge:
    print("Buy cheese")
numbers = [4, 11, 7, 20, 3]
big = []
for n in numbers:
    if n > 5:
        big.append(n)
print(big)      # [11, 7, 20]

The filtering pattern: start with an empty list [], loop, and append only the items that pass the test.

Common mistake: changing a list (removing items) while looping over it. Items get skipped. Build a new list instead, as in the example.

If you need the position as well as the item, use for i, item in enumerate(my_list):. i will be 0, 1, 2, ...

sum(list), max(list) and min(list) are built-in shortcuts for number lists.