A for loop lets you repeat code (a branch). To repeat Python code, the for keyword can be used. This lets you iterate over one or more lines of code.

Sometimes you need to execute a block of code more than once, for loops solve that problem.

Related Course: Complete Python Programming Course & Exercises

The Python for Loop

The for loop can iterate over a collection. Python’s for loop looks this way:

for <var> in <iterable>:
<statement(s)>

In this code, <iterable> is a collection. That can be a list of numbers, a list of strings or even a string itself.

<statement(s)> is just code, this can be one line or more lines of code.

<var> is the loop variable, the current element, this changes each reptition.

Here is an example:

>>> sounds = ['meow','woof','bark']
>>> for s in sounds:
... print(s)
...
meow
woof
bark
>>>

In this example <iterable> is sounds, s is the var and there is one statement: print(s).

The statement will be repeat (iterate) for every element of the collection.

The for loop works for any collection, see the code below:

>>> a = [1,2,3]
>>> for i in a:
... print(f"i is {i}")
...
i is 1
i is 2
i is 3

>>> a = "hello"
>>> for i in a:
... print(f"i is {i}")
...
i is h
i is e
i is l
i is l
i is o

Collections include lists, tuples, strings and sets.

python for loop

Related Course: Complete Python Programming Course & Exercises

The range() function

To repeat code n times you can create a for loop with the range() function.

for i in range(1,11):
print(i)

In this loop the variable i is used as an index: it increases every repetition.

The range function starts with 1 because we want to count from 1 and ends with 10 (11 is not included). The last number (11) is not included.

python range function

The range() function generates numbers:

>>> list(range(4))
[0, 1, 2, 3]

>>> list(range(3))
[0, 1, 2]

>>> list(range(3,7))
[3, 4, 5, 6]

So you pass this as iterable in:

for <var> in <iterable>:
<statement(s)>

For loop flow chart

The flow chat below shows a for loop:

for loop control flow graph in python

The code inside the for loop code block is repeated while the condition is True.

If the condition turns into False, it ends repeating.

Every iteration (round), the index variable i increases.

Related Course: Complete Python Programming Course & Exercises

Nested loops

You can have loop inside loops. That makes the loops a combined loop:

for i in range(0,10):
for j in range(0,10):
print(i,' ',j)

This is sometimes called a multidimensional loop.

It will output coordinates (0,0) to (9,9).

The more for loops you put inside for loops, the more confusing it gets. It’s a general practice to not put more than two or three loops inside each other, as it becomes to complicated to understand.

Iterate with for loop

Iterating over integer indices is not Pythonic and overcomplicated. If you have a list, you can simply iterate over the list this way:

myList = [1,2,3]
for item in myList:
print(item)

This executes the code block just the same as the equivalent code:

myList = [1,2,3]
for i in range(0,len(myList)):
print(myList[i])

But is a lot easier and more Pythonic to read.

Iterate through a dictionary

If you want to iterate over a dictionary, you can do so by it’s key and the use it’s key to request it’s value.

ydict  = {1:'one', 2:'two', 3:'three'}
for key in mydict:
print(key, mydict[key])

Not only are these ways easier to read, but they actually run faster because the other loops need the range() function to be called.

Iterables

An iterable is any object that you can iterate. You can check if an object is iterable by calling the iter function.
Lets try that:

>>> s = ['meow','woof','bark'] # list
>>> iter(s)
<list_iterator object at 0x7ff77d631490>

>>> s = [1,2,3] # list
>>> iter(s)
<list_iterator object at 0x7ff77d631450>

>>> s= 'hello' # string
>>> iter(s)
<str_iterator object at 0x7ff77d6314d0>

>>> s = { 'meow','woof' } # set
>>> iter(s)
<set_iterator object at 0x7ff77d62ae10>

>>> s = {'one':1, 'two':2 } # tuple
>>> iter(s)
<dict_keyiterator object at 0x7ff77d737cb0>
>>>

So many types of variables are iterables. But not every variable or object is iterable.

If a variable is not iterable, iter() will throw an exception.

>>> s = 2
>>> iter(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

So simple single variables like an integer or float are not iterable. A function is not an iterable either.

Iterable types include list, tuple, string, dict and set.

Iterators

If you have an iterable, you can call the iter() function to iterate over the iterable.

The next() function can be used to get the next item.

>>> s = ['meow','woof','bark']
>>> it = iter(s)
>>> next(it)
'meow'
>>> next(it)
'woof'
>>> next(it)
'bark'
>>>

python iterator and next function

If there are no more items, it will throw a StopIteration exception.

>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>

You can use iter() and next() on any iterable.

>>> s = "hello"
>>> it = iter(s)
>>> next(it)
'h'
>>> next(it)
'e'
>>> next(it)
'l'
>>> next(it)
'l'
>>> next(it)
'o'
>>>

Break and continue

It’s possible to alterate the loop behavior. You may know about this from the while loop.

The break keyword exists the for loop, before it’s finished.

>>> a = ['meow','grrr','bark','woof']
>>> for i in a:
... if 'g' in i:
... break
... print(i)
...
meow
>>>

You can do this for numeric loops too:

>>> a = list(range(6))
>>> for i in a:
... if i == 5:
... break
... print(f"i is {i}")
...
i is 0
i is 1
i is 2
i is 3
i is 4

continue jumps to the next iteration:

>>> a = ['meow','grrr','bark','woof']
>>> for i in a:
... if 'g' in i:
... continue
... print(i)
...
meow
bark
woof
>>>

If you are a Python beginner, then I highly recommend this book.

 Download exercises