TracksPractical Coding FoundationsWorking With DataLooping Through Collections(6 of 9)

Looping Through Collections

The real power of collections comes when you combine them with loops. Instead of accessing items one by one, you can process entire collections with just a few lines of code.

Looping Through Lists

The simplest pattern gives you each item in turn:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

The variable fruit takes on each value in the list, one at a time. You can name this variable anything — fruit, item, x — but descriptive names make code clearer.

Getting the Index Too

Sometimes you need both the item and its position. Use enumerate():

fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

Output:

0: apple
1: banana
2: cherry

The enumerate() function returns pairs of (index, item), which you unpack into two variables.

Looping Through Dictionary Keys

When you loop over a dictionary directly, you get its keys:

person = {"name": "Alice", "age": 30, "city": "Boston"}
for key in person:
    print(key)

Output:

name
age
city

Looping Through Keys and Values

Usually you want both. Use .items():

person = {"name": "Alice", "age": 30, "city": "Boston"}
for key, value in person.items():
    print(f"{key}: {value}")

Output:

name: Alice
age: 30
city: Boston

Just Values

If you only need values, use .values():

person = {"name": "Alice", "age": 30, "city": "Boston"}
for value in person.values():
    print(value)

Combining With Conditions

Loops and conditions work beautifully together:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
    if num % 2 == 0:
        print(f"{num} is even")

This pattern — loop through a collection, check each item, act on matches — is one of the most common in programming.

See More

You need to be signed in to leave a comment and join the discussion