✦ Python Foundations Collections module

Concept 12 · Iterating over Collections

Visit every value.
Let a loop do the work.

Lists and tuples are visited in order, sets without relying on order, and dictionaries through keys, values, or key-value pairs.

01 Learn02 Try03 Predict

A for loop can visit each value in a collection.

Lists and tuples are visited in order, sets without relying on order, and dictionaries through keys, values, or key-value pairs.

names = ["Ana", "Marko"]
for name in names:
    print(name)

Each turn through the loop assigns the next collection value to name.

Try changing one value, then explain which part of the collection changed and why.

↳

Keep this in mind: Read the collection operation before predicting the result.

Try it
student = {
    "name": "Ana",
    "course": "Python",
    "city": "Novi Sad"
}

for key, value in student.items():
    print(key, ":", value)

Run the example, then change one value and observe the result.

Lists and tuples
for value in ("red", "blue"):
    print(value)

A loop visits list and tuple items one at a time in their order.

Sets do not promise an order
for tag in {"python", "django"}:
    print(tag)

A set can be iterated, but its items do not have reliable positions or a fixed display order.

Dictionary keys, values, and pairs
for key in student:
    print(key)

for value in student.values():
    print(value)

Iterating over a dictionary gives keys. Use values() for values and items() to unpack each key and value together.

Python Playground

Loading Python runtime…

Edit the example and run it in your browser.

iterating_over_collections.pyPython
OutputWaiting for Python
The browser runtime is loading. You can still edit the example code.

Pyodide runs Python in a browser Web Worker. It is stopped and restarted if code keeps running. Browser execution is not a complete security boundary; do not enter secrets or rely on it for untrusted code isolation.

What will this program print?

Read each operation before choosing an answer.

numbers = [2, 4, 6]
total = 0

for number in numbers:
    total += number

print(total)
print(len(numbers))
Choose the output
Sloby, the Python AI Tutor mascot

Your learning mentor

Ask Sloby about this concept

Describe what feels unclear and Sloby will guide your reasoning.

Hi! I'm Sloby. Let's explore this Python concept together.

What will this program print, and why? Explain .items(), key-value unpacking, and the total.

scores = {"Ana": 8, "Marko": 6, "Jelena": 10}
total = 0

for name, score in scores.items():
    total += score

print(total)
print(len(scores))
Python AI Tutor · Learn by understanding, not just by running code.