Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: For Loops in Python (Definite Iteration)
This tutorial will show you how to perform definite iteration with a Python for loop.
In the previous tutorial in this introductory series, you learned the following:
- Repetitive execution of the same block of code over and over is referred to as iteration.
- There are two types of iteration:
- Definite iteration, in which the number of repetitions is specified explicitly in advance
- Indefinite iteration, in which the code block executes until some condition is met
- In Python, indefinite iteration is performed with a
whileloop.
Here’s what you’ll cover in this tutorial:
-
You’ll start with a comparison of some different paradigms used by programming languages to implement definite iteration.
-
Then you will learn about iterables and iterators, two concepts that form the basis of definite iteration in Python.
-
Finally, you’ll tie it all together and learn about Python’s
forloops.
Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.
Take the Quiz: Test your knowledge with our interactive “The Python for Loop” quiz. Upon completion you will receive a score so you can track your learning progress over time:
A Survey of Definite Iteration in Programming
Definite iteration loops are frequently referred to as for loops because for is the keyword that is used to introduce them in nearly all programming languages, including Python.
Historically, programming languages have offered a few assorted flavors of for loop. These are briefly described in the following sections.
Numeric Range Loop
The most basic for loop is a simple numeric range statement with start and end values. The exact format varies depending on the language but typically looks something like this:
for i = 1 to 10
<loop body>
Here, the body of the loop is executed ten times. The variable i assumes the value 1 on the first iteration, 2 on the second, and so on. This sort of for loop is used in the languages BASIC, Algol, and Pascal.
Three-Expression Loop
Another form of for loop popularized by the C programming language contains three parts:
- An initialization
- An expression specifying an ending condition
- An action to be performed at the end of each iteration.
This type of loop has the following form:
for (i = 1; i <= 10; i++)
<loop body>
Technical Note: In the C programming language, i++ increments the variable i. It is roughly equivalent to i += 1 in Python.
This loop is interpreted as follows:
- Initialize
ito1. - Continue looping as long as
i <= 10. - Increment
iby1after each loop iteration.
Three-expression for loops are popular because the expressions specified for the three parts can be nearly anything, so this has quite a bit more flexibility than the simpler numeric range form shown above. These for loops are also featured in the C++, Java, PHP, and Perl languages.
Collection-Based or Iterator-Based Loop
This type of loop iterates over a collection of objects, rather than specifying numeric values or conditions:
for i in <collection>
<loop body>
Each time through the loop, the variable i takes on the value of the next object in <collection>. This type of for loop is arguably the most generalized and abstract. Perl and PHP also support this type of loop, but it is introduced by the keyword foreach instead of for.
Further Reading: See the For loop Wikipedia page for an in-depth look at the implementation of definite iteration across programming languages.
The Python for Loop
Of the loop types listed above, Python only implements the last: collection-based iteration. At first blush, that may seem like a raw deal, but rest assured that Python’s implementation of definite iteration is so versatile that you won’t end up feeling cheated!
Shortly, you’ll dig into the guts of Python’s for loop in detail. But for now, let’s start with a quick prototype and example, just to get acquainted.
Python’s for loop looks like this:
for <var> in <iterable>:
<statement(s)>
<iterable> is a collection of objects—for example, a list or tuple. The <statement(s)> in the loop body are denoted by indentation, as with all Python control structures, and are executed once for each item in <iterable>. The loop variable <var> takes on the value of the next element in <iterable> each time through the loop.
Here is a representative example:
>>> a = ['foo', 'bar', 'baz']
>>> for i in a:
... print(i)
...
foo
bar
baz
In this example, <iterable> is the list a, and <var> is the variable i. Each time through the loop, i takes on a successive item in a, so print() displays the values 'foo', 'bar', and 'baz', respectively. A for loop like this is the Pythonic way to process the items in an iterable.
But what exactly is an iterable? Before examining for loops further, it will be beneficial to delve more deeply into what iterables are in Python.
Iterables
In Python, iterable means an object can be used in iteration. The term is used as:
- An adjective: An object may be described as iterable.
- A noun: An object may be characterized as an iterable.
If an object is iterable, it can be passed to the built-in Python function iter(), which returns something called an iterator. Yes, the terminology gets a bit repetitive. Hang in there. It all works out in the end.
Each of the objects in the following example is an iterable and returns some type of iterator when passed to iter():
>>> iter('foobar') # String
<str_iterator object at 0x036E2750>
>>> iter(['foo', 'bar', 'baz']) # List
<list_iterator object at 0x036E27D0>
>>> iter(('foo', 'bar', 'baz')) # Tuple
<tuple_iterator object at 0x036E27F0>
>>> iter({'foo', 'bar', 'baz'}) # Set
<set_iterator object at 0x036DEA08>
>>> iter({'foo': 1, 'bar': 2, 'baz': 3}) # Dict
<dict_keyiterator object at 0x036DD990>
These object types, on the other hand, aren’t iterable:
>>> iter(42) # Integer
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
iter(42)
TypeError: 'int' object is not iterable
>>> iter(3.1) # Float
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
iter(3.1)
TypeError: 'float' object is not iterable
>>> iter(len) # Built-in function
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
iter(len)
TypeError: 'builtin_function_or_method' object is not iterable
All the data types you have encountered so far that are collection or container types are iterable. These include the string, list, tuple, dict, set, and frozenset types.
But these are by no means the only types that you can iterate over. Many objects that are built into Python or defined in modules are designed to be iterable. For example, open files in Python are iterable. As you will see soon in the tutorial on file I/O, iterating over an open file object reads data from the file.
In fact, almost any object in Python can be made iterable. Even user-defined objects can be designed in such a way that they can be iterated over. (You will find out how that is done in the upcoming article on object-oriented programming.)
Iterators
Okay, now you know what it means for an object to be iterable, and you know how to use iter() to obtain an iterator from it. Once you’ve got an iterator, what can you do with it?
An iterator is essentially a value producer that yields successive values from its associated iterable object. The built-in function next() is used to obtain the next value from in iterator.
Here is an example using the same list as above:
>>> a = ['foo', 'bar', 'baz']
>>> itr = iter(a)
>>> itr
<list_iterator object at 0x031EFD10>
>>> next(itr)
'foo'
>>> next(itr)
'bar'
>>> next(itr)
'baz'
In this example, a is an iterable list and itr is the associated iterator, obtained with iter(). Each next(itr) call obtains the next value from itr.
Notice how an iterator retains its state internally. It knows which values have been obtained already, so when you call next(), it knows what value to return next.
What happens when the iterator runs out of values? Let’s make one more next() call on the iterator above:
>>> next(itr)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
next(itr)
StopIteration