for

A loop that goes through the successive items of a sequence or other iterable object.

On this page

Example

#
Python
courses = ["HTML", "CSS", "Python"]

for course in courses:
    print(f"Course: {course}")

for i in range(3):
    print(i, end=" ")
print()
Resultsaved result, you can check it
Course: HTML
Course: CSS
Course: Python
0 1 2

Definition and usage

#

A for loop in Python goes through the items of any iterable object: a list, a string, a dictionary, a set, or a range of numbers from range(). On each pass, the loop variable gets the next item.

range() is for looping over numbers, and when you need both the index and the item, use enumerate(). You can go through two lists at once with zip().

A loop can have an else block, which runs when the loop finishes normally, meaning without being interrupted by break. This is handy when searching for something.

Syntax

#
Syntax
for element in collection:
    ...

More examples

#
enumerate, zip, and dictionaries
Python
names = ["Emma", "Jack"]
scores = [92, 78]

for position, (name, score) in enumerate(zip(names, scores), start=1):
    print(f"{position}. {name}: {score}")

levels = {"html": 11, "python": 12}
for course, modules in levels.items():
    print(course, modules)
Resultsaved result, you can check it
1. Emma: 92
2. Jack: 78
html 11
python 12
A loop with else
Python
numbers = [3, 7, 11]
for n in numbers:
    if n % 2 == 0:
        print("Found an even number:", n)
        break
else:
    print("No even numbers found")
Resultsaved result, you can check it
No even numbers found

Good practices

#
  • Do not write for i in range(len(my_list)) when you need the items. Use for element in my_list or enumerate().
  • Do not modify a list while looping over it. Build a new list instead, ideally with a list comprehension.

Related entries

#

Spotted a mistake or missing an example? Write to us.