PythonSyntax and keywords
for
A loop that goes through the successive items of a sequence or other iterable object.
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
#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
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. Usefor element in my_listorenumerate(). - Do not modify a list while looping over it. Build a new list instead, ideally with a list comprehension.
Related entries
#- whileA loop that repeats a block of code while a condition is true.
- range()Creates a sequence of integers, most often for a for loop.
- enumerate()Adds a counter to items while looping over them.
- zip()Pairs up (or groups into tuples) the matching items of several collections.
- break and continueBreaking out of a loop, or skipping to its next pass.
- iter()Returns an iterator for a collection, an object that hands out its items one at a time. This is the mechanism behind the for loop.
Spotted a mistake or missing an example? Write to us.