Python’s for loop allows you to iterate over the items in a collection, such as lists, tuples, strings, and dictionaries. The for loop syntax declares a loop variable that takes each item from the collection in each iteration. This loop is ideal for repeatedly executing a block of code on each item in the collection. You can also tweak for loops further with features like break, continue, and else.
By the end of this tutorial, you’ll understand that:
- Python’s
forloop iterates over items in a data collection, allowing you to execute code for each item. - To iterate from
0to10, you use thefor index in range(11):construct. - To repeat code a number of times without processing the data of an iterable, use the
for _ in range(times):construct. - To do index-based iteration, you can use
for index, value in enumerate(iterable):to access both index and item.
In this tutorial, you’ll gain practical knowledge of using for loops to traverse various collections and learn Pythonic looping techniques. You’ll also learn how to handle exceptions and use asynchronous iterations to make your Python code more robust and efficient.
Get Your Code: Click here to download the free sample code that shows you how to use for loops in Python.
Take the Quiz: Test your knowledge with our interactive “Python for Loops: The Pythonic Way” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Python for Loops: The Pythonic WayIn this quiz, you'll test your understanding of Python's for loop. You'll revisit how to iterate over items in a data collection, how to use range() for a predefined number of iterations, and how to use enumerate() for index-based iteration.
Getting Started With the Python for Loop
In programming, loops are control flow statements that allow you to repeat a given set of operations a number of times. In practice, you’ll find two main types of loops:
forloops are mostly used to iterate a known number of times, which is common when you’re processing data collections with a specific number of data items.whileloops are commonly used to iterate an unknown number of times, which is useful when the number of iterations depends on a given condition.
Python has both of these loops and in this tutorial, you’ll learn about for loops. In Python, you’ll generally use for loops when you need to iterate over the items in a data collection. This type of loop lets you traverse different data collections and run a specific group of statements on or with each item in the input collection.
In Python, for loops are compound statements with a header and a code block that runs a predefined number of times. The basic syntax of a for loop is shown below:
for variable in iterable:
<body>
In this syntax, variable is the loop variable. In each iteration, this variable takes the value of the current item in iterable, which represents the data collection you need to iterate over. The loop body can consist of one or more statements that must be indented properly.
Here’s a more detailed breakdown of this syntax:
foris the keyword that initiates the loop header.variableis a variable that holds the current item in the input iterable.inis a keyword that connects the loop variable with the iterable.iterableis a data collection that can be iterated over.<body>consists of one or more statements to execute in each iteration.
Here’s a quick example of how you can use a for loop to iterate over a list:
>>> colors = ["red", "green", "blue", "yellow"]
>>> for color in colors:
... print(color)
...
red
green
blue
yellow
In this example, color is the loop variable, while the colors list is the target collection. Each time through the loop, color takes on a successive item from colors. In this loop, the body consists of a call to print() that displays the value on the screen. This loop runs once for each item in the target iterable. The way the code above is written is the Pythonic way to write it.
However, what’s an iterable anyway? In Python, an iterable is an object—often a data collection—that can be iterated over. Common examples of iterables in Python include lists, tuples, strings, dictionaries, and sets, which are all built-in data types. You can also have custom classes that support iteration.
Note: Python has both iterables and iterators. Iterables support the iterable protocol consisting of the .__iter__() special method. Similarly, iterators support the iterator protocol that’s based on the .__iter__() and .__next__() special methods.
Both iterables and iterators can be iterated over. All iterators are iterables, but not all iterables are iterators. Python iterators play a fundamental role in for loops because they drive the iteration process.
A deeper discussion on iterables and iterators is beyond the scope of this tutorial. However, to learn more about them, check out the Iterators and Iterables in Python: Run Efficient Iterations tutorial.
You can also have a loop with multiple loop variables:
>>> points = [(1, 4), (3, 6), (7, 3)]
>>> for x, y in points:
... print(f"{x = } and {y = }")
...
x = 1 and y = 4
x = 3 and y = 6
x = 7 and y = 3
In this loop, you have two loop variables, x and y. Note that to use this syntax, you just need to provide a tuple of loop variables. Also, you can have as many loop variables as you need as long as you have the correct number of items to unpack into them. You’ll also find this pattern useful when iterating over dictionary items or when you need to do parallel iteration.
Sometimes, the input iterable may be empty. In that case, the loop will run its header once but won’t execute its body:
>>> for item in []:
... print(item)
...
In this example, the target iterable is an empty list. The loop checks whether the iterable has items. If that’s the case, then the loop runs once for each item. If the iterable has no items, then the loop body doesn’t run, and the program’s execution flow jumps onto the statement after the loop.
Now that you know the basic syntax of for loops, it’s time to dive into some practical examples. In the following section, you’ll learn how to use for loops with the most common built-in data collections in Python.
Traversing Built-in Collections in Python
When writing Python code, you’ll often need to iterate over built-in data types such as lists, tuples, strings, numeric ranges, dictionaries, and sets. All of them support iteration, and you can feed them into a for loop. In the next sections, you’ll learn how to tackle this requirement in a Pythonic way.
Sequences: Lists, Tuples, Strings, and Ranges
When it comes to iterating over sequence data types like lists, tuples, strings, and ranges, the iteration happens in the same order that the items appear in the sequence. Consider the following example where you iterate over the numbers in a list:
>>> numbers = [1, 2, 3, 4]
>>> for number in numbers:
... print(number)
...
1
2
3
4
In this example, the iteration goes through the list in the definition order, starting with 1 and ending with 4. Note that to iterate over a sequence in Python, you don’t need to be aware of the index of each item as in other languages where loops often rely on indices.
Often, you use plural nouns to name lists. This naming practice allows you to use singular nouns as the loop variable, making your code descriptive and readable.
Note: To learn more about using lists, check out Python’s list Data Type: A Deep Dive With Examples.
You’ll note the same behavior with other built-in sequences:
>>> person = ("Jane", 25, "Python Dev", "Canada")
>>> for field in person:
... print(field)
...
Jane
25
Python Dev
Canada
>>> text = "abcde"
>>> for character in text:
... print(character)
...
a
b
c
d
e
>>> for index in range(5):
... print(index)
...
0
1
2
3
4
In these examples, you iterate over a tuple, string, and numeric range. Again, the loop traverses the sequence in the order of definition.
Note: For more information about tuples, strings, and ranges, you can check out the following tutorials:
Tuples are often used to represent rows of data. In the example above, the person tuple holds data about a person. You can iterate over each field using a readable loop.
When it comes to iterating over string objects, the for loop lets you process the string on a character-by-character basis. Finally, iterating over a numeric range is sometimes a requirement, especially when you need to iterate a given number of times and need control over the consecutive index.
Collections: Dictionaries and Sets
When traversing dictionaries with a for loop, you’ll find that you can iterate over the keys, values, and items of the dictionary at hand.
Note: To learn more about dictionary iteration, check out the How to Iterate Through a Dictionary in Python tutorial.
You’ll have two different ways to iterate over the keys of a dictionary. You can either use:
- The dictionary directly
- The
.keys()method
The following examples show how to use these two approaches:
>>> students = {
... "Alice": 89.5,
... "Bob": 76.0,
... "Charlie": 92.3,
... "Diana": 84.7,
... "Ethan": 88.9,
... }
>>> for student in students:
... print(student)
...
Alice
Bob
Charlie
Diana
Ethan
>>> for student in students.keys():
... print(student)
...
Alice
Bob
Charlie
Diana
Ethan
In these examples, you first iterate over the keys of a dictionary using the dictionary directly in the loop header. In the second loop, you use the .keys() method to iterate over the keys. While both approaches are equivalent, the first one is more commonly used, whereas the second might be more readable and explicit.
In both loops, you can access the dictionary values using the keys:
>>> for student in students:
... print(student, "->", students[student])
...
Alice -> 89.5
Bob -> 76.0
Charlie -> 92.3
Diana -> 84.7
Ethan -> 88.9
To access the values in this type of iteration, you can use the original dictionary and a key lookup operation, as shown in the highlighted line.
You can use the .values() method to feed the for loop when you need to iterate over the values of a dictionary: