Python For Loops—A Complete Guide & Useful Examples

In Python, a for loop is used for iterating over an iterable collection of values such as a list, a tuple, a dictionary, a set, or a string.

The for loop uses the following syntax:

for elem in iterable:
    # actions

Where:

  • elem is an element that is part of an iterable, such as a list.
  • iterable is an iterable object which can be looped through.
  • # actions represents the body of the loop. You can run any valid Python code here.

The for loop works such that it starts looping through the iterable and one by one assigns each element to a temporary variable called elem.

Let’s see a simple example where we loop through a list of strings:

animals = ["monkey", "lion", "elephant"]

for animal in animals:
    print(animal)

Output:

monkey
lion
elephant

Using the for loop you can execute statements, once for each item in the sequence.

As you might imagine, looping through an iterable object is a really common thing to do.

Thus it is important you understand how to utilize loops in your code.

In this guide, you learn for loops with useful and practical examples.

What Is a For Loop in Python

One of the essentials of programming is being able to repeat a specific action a number of times.

For instance, you could be asked to create a list of numbers squared from 1 to 1000. Producing a list like this manually would take a day. However, with a loop, you can get it done in milliseconds.

As you can imagine, any computer program has to deal with tons of data.

As another example, imagine a social media app with millions of users wanting to show you the users that are located in the same city as you. To do this, the app can loop through the list of all the users and only pick the ones that are in the same city. For a computer, this kind of operation takes very little time.

This kind of task would not be possible without loops.

In Python, there are two types of loops:

  • For loops
  • While loops

In this guide, we are going to focus on for loops, which in many projects is the most commonly used loop type in Python.

How to Create a For Loop in Python

The blueprint for creating a for loop in Python looks like this:

for var in iterable:
    # actions

Where:

  1. iterable is a collection of elements, such as a list or a tuple.
  2. The # actions part is the body of the loop. Here you can run any valid Python code.
  3. var is a temporary variable. The loop assigns each element in the iterable to this variable one by one. You can use the var in the body of the loop.

All of this probably sounds cryptic.

Thus, let’s see an example.

Perhaps the easiest example to demonstrate for loops is by printing numbers from 1 to 5:

for number in [1, 2, 3, 4, 5]:
    print(number)

Output:

1
2
3
4
5

This for loop works such that it:

  1. Picks each number from [1, 2, 3, 4, 5]
  2. Assigns the number to a temporary variable called number.
  3. Prints the number.

In other words, the loop simply runs print(number) for each number in the list.

As you learned, you can place any valid Python code into the body of the loop.

Let’s demonstrate this with another example.

This time, let’s print each number squared:

for number in [1, 2, 3, 4, 5]:
    square = number * number
    print(square)

Output:

1
4
9
16
25

As you can see, now we took the number and squared it in the loop before printing it out.

What Can Be Looped in Python?

In Python, you can loop through anything that is iterable.

But what is iterable?

Because this is a beginner-friendly guide, we are not going to worry about the details of what is iterable. Instead, you will learn the most common iterable types in Python.

In Python, common examples of iterables are:

  • Lists
  • Strings
  • Dictionaries
  • Tuples
  • Sets

All these data types are “loopable” in Python.

For example, a string is an iterable collection of characters. This means you can iterate over a string character by character.

For example, let’s print out each character in a string using a for loop:

for x in "Apple":
  print(x)

Output:

A
p
p
l
e
looping through the characters of a string and printing them on separate lines

To learn how iterables work behind the scenes, feel free to read this article.

The range() Function in Python

It is quite common for you to want to create a range of numbers and loop through it.

For instance, if you want to count from 1 to 1000 you do not want to create a list and place 1000 numbers in it.

Instead, you can use the built-in range() function.

This function is designed to make it easy to create an iterable range of numbers.

For example, let’s print numbers from 1 to 10 using range():

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

Output:

1
2
3
4
5
6
7
8
9
10

As you can see, the first parameter of the range() function is 1 as expected. But the last parameter is 11. This is because the range is exclusive. In other words, the last value is excluded from the result.

The range() function is commonly used within for loops in Python.

Here is a complete guide to using the range() function in Python.

Controlling the Flow of a For Loop

The for loop runs from top to bottom.

However, sometimes you might want to alter the flow of the loop.

For instance, if your loop has code that you do not want to run if a condition is not met, you want to jump out of the current iteration.

Also, sometimes you want to completely stop the loop prematurely.

To control the flow of a for loop in Python, you can use the control flow statements:

  1. continue
  2. break

Let’s take a closer look at how these work.

Continue Statement

In Python, the continue statement allows you to stop the current iteration of a for loop and jump to the next one.

This is useful if you want to prevent the loop from running a specific piece of code on a certain condition.

For example, let’s print the odd numbers in a range of numbers from 1 to 10:

for number in range(1, 11):
    if number % 2 == 0:
        continue
    print(number)

This loop skips the print() function call when it encounters an even number (a number divisible by 2):

1
3
5
7
9

This is a great way to demonstrate how you can use the continue statement to jump out of the current iteration.

However, the above example does not need to use the continue statement.

Instead, it would be much cleaner to check if the number is not even and print it:

for number in range(1, 11):
    if number % 2 != 0:
        print(number)

Output:

1
3
5
7
9

Now the code is more readable.

So is the continue statement useless then?

Absolutely not.

You can use the continue statement to avoid nested if-else statements and to help with handling exceptions.

To learn more about when you can use the continue statement, feel free to read this article.

Next, let’s examine how the break statement works.

Break Statement

Sometimes you need to terminate a for loop altogether.

To do this, use the break keyword.

This literally breaks out of the loop.

For example, let’s escape a for loop if we encounter a string called “elephant” in a list of animal names:

animals = ["monkey", "lion", "elephant", "rhino", "jackal"]

for animal in animals:
    if animal == "elephant":
        print("elephant found. Terminating the loop")
        break
    print(animal)

Output:

monkey
lion
elephant found. Terminating the loop

As you can see, the rest of the animals were not printed out. This is because the loop was terminated when an elephant was encountered.

Using the break statement is useful if you want to save resources.

This can be seen in the above example as well.

Printing the rest of the animals is useless if we are looking for an elephant and we already found it.

Now imagine you ran some other computationally heavy tasks during each iteration. By breaking the loop you save the loop from running unnecessary code.

Next up, let’s see some examples of for loops in Python.

Else Statement in a For Loop

You can place an else statement at the end of a for loop.

For example:

for x in range(3):
    print(x)
else:
    print("It's over")

Output:

0
1
2
It's over

You are not going to use an else block in a for loop that often. However, it is important to know such an option exists.

Here is a complete guide to using an else block in a loop in Python.

Notice that the working principle of the else block in a for loop is counterintuitive.

The else block of a for loop runs only if the loop was not interrupted by a break statement!

Let’s have a look at an example.

Here we are looping through a list of numbers until a number 3 is encountered:

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    if number == 3:
        break
    print(number)
else:
    print("The loop ran from start to finish.")

Output:

1
2

As you can see, the else block was not executed because we broke out of the loop before running through all the numbers.

However, if we modify the code a bit such that we terminate the loop if the number is 6, we get a different result:

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    if number == 6:
        break
    print(number)
else:
    print("The loop ran from start to finish.")

Output:

1
2
3
4
5
The loop ran from start to finish.

Here the loop iterated over all the numbers in a list from start to finish. Thus, the else block was executed.

As a matter of fact, an else block in a for loop is a confusing naming decision. Instead of else, Python developers could have come up with a new keyword like nobreak.

Nested For Loops in Python

As you learned earlier in this guide, you can place any valid Python code into the body of a for loop.

This means you can also add another loop inside the loop.

Placing a loop inside another is quite common in Python. A loop that has a loop (or multiple loops) inside of it is called a nested loop.

For example, it is common to represent a matrix as a list of lists in Python. In other words, each list represents a row of a matrix. (Do not worry if you don’t know what is a matrix. In this context it is just a list of lists.)

To access each number in the matrix you need to create a nested loop that:

  1. Picks a list one by one from the matrix.
  2. Picks a number one by one from the list.

For example, let’s print the contents of a matrix:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for row in matrix:
    for number in row:
        print(number)

Output:

1
2
3
4
5
6
7
8
9

Here each inner list is assigned to a variable called row.

Then each number in the row is assigned to a variable called number.

The number is then printed out in the nested loop’s body.

How to Create an Empty For Loop

You may have noticed you can’t leave a for loop empty. You are always required to add some code into the body of the loop. Otherwise, there is going to be an error.

However, sometimes you may want to leave the implementation of a loop “blank” or to have a placeholder for a loop.

In this case, you can use a special pass statement in the loop body to skip the implementation of it.

As a matter of fact, you can use the pass statement in other code constructs as well, such as in functions or classes.

To use the pass statement, place the pass keyword inside the body of the loop.

For instance, let’s create a for loop that iterates over a list of numbers but does not do anything:

for x in [0, 1, 2]:
  pass

Now you can run this piece of code without errors.

If you take away the pass statement, you have to write some code to the loop or it fails.

One-Liner For Loops

It is time to learn how to make your code readable by introducing a one-liner for loops.

Thus far you have seen nicely structured for loops that span across multiple lines of code.

However, in some situations, the for loops can be compressed into one-liner expressions called comprehensions.

Python supports four different types of comprehensions for the common iterable types:

Each type of comprehension is similar to one another.

In the next sections, you are going to learn how each type of comprehension works.

List Comprehensions in Python

In Python, you can use list comprehension to shorten a for loop over a list.

The list comprehension follows this general syntax:

[action(item) for item in list if condition]

The result of a list comprehension is a new list of values.

List comprehensions are usually used to convert a list into another.

The best way to explain how the above list comprehension works is by seeing the corresponding regular for loop:

for item in list:
    if condition:
        action(item)

As you can see, the list comprehension is just a compact way to write the above for loop.

Notice that obviously, the condition is not mandatory. If there is no condition you want to check, the comprehension looks simply like this:

[action(item) for item in list]
Rearranging a for loop to a list comprehension

Anyway, to make any sense of the list comprehension, you need to see some examples.

Let’s start with a regular for loop. In this example, we are going to drop negative values from a list of numbers.

Here is how it looks in code:

numbers = [4, -2, 7, -4, 19]

new_nums = []
for num in numbers:
    if num > 0:
        new_nums.append(num)

print(new_nums)

Output:

[4, 7, 19]

Now, let’s repeat the example.

This time, let’s use a list comprehension:

numbers = [4, -2, 7, -4, 19]
new_nums = [num for num in numbers if num > 0]
print(new_nums)

Output:

[4, 7, 19]

As you can see, the list comprehension only took 1 line of code instead of the 4 lines taken by the regular for loop.

As another example, let’s print numbers with a list comprehension:

numbers = [1, 2, 3]

[print(number) for number in numbers]

Output:

1
2
3

However, using a list comprehension without generating a new list is not practical. Thus, if you are only looping through a list without creating a new list, use a regular for loop.

Speaking of the use cases for list comprehensions, it is up to a debate as to when you should use list comprehensions in Python.

As a general rule of thumb, you can use comprehensions only if they can improve the code readability. Also, it is not wrong to never use list comprehensions (or other comprehensions).

If you are a beginner, it is good to know such comprehensions exist because some developers use them quite often.

However, you do not need to worry about using them if you don’t like to.

Next, let’s move on to dictionary comprehensions.

Dictionary Comprehensions in Python

Python has a shorthand for looping through dictionaries too.

This is known as dictionary comprehension.

The dictionary comprehension works similar to list comprehension.

Let’s see an example.

Example—How to Create a Dictionary From a List Using Dictionary Comprehension

Say you want to create a dictionary based on a numbers list.

In the new dictionary, a number is a key and the value is the number as a string.

In addition, you only want to include even numbers.

Here is how it looks in code:

nums = [10, 20, 30, 40, 50]

dict = {}
for num in nums:
    if num % 2 == 0:
        dict[num] = str(num)

print(dict)

Output:

{10: '10', 20: '20', 30: '30', 40: '40', 50: '50'}

This works really well.

However, using a dictionary comprehension, everything can be done in one line:

dict = {num: str(num) for num in nums if num % 2 == 0}
print(dict)

Output:

{10: '10', 20: '20', 30: '30', 40: '40', 50: '50'}

Notice how similar a dictionary comprehension is to a list comprehension.

The only differences are:

  • You need to use curly brackets instead of square brackets.
  • You need to map a key to a value for each element.
Example—How to Operate on an Existing Dictionary Using Dictionary Comprehensions

In the previous example, you turned a list into a dictionary using dictionary comprehension.

But how about performing dictionary comprehension on a dictionary?

Let me show you another example.

In this example, you square the number values of the dictionary into a new dictionary object:

data = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
squared = {k:v*v for (k,v) in data.items()}

print(squared)

Output:

{'a': 1, 'b': 4, 'c': 9, 'd': 16, 'e': 25}

This is once again a simpler version of a for loop with just one line of code.

The basic structure of dictionary comprehension looks like this

{key:value for (key,value) in dict if condition}

Set Comprehensions in Python

Set comprehension is like a list comprehension for sets.

For instance, let’s move all the even numbers from a list into a set.

Here is a basic for loop approach to the problem:

numbers = [13, 21, 14, 24, 53, 62]
filtered_nums = set()

for num in numbers: 
    if num % 2 == 0: 
        filtered_nums.add(num) 

print(filtered_nums)

Output:

{24, 62, 14}

But using set comprehension the code becomes more concise:

filtered_nums = {num for num in numbers if num % 2 == 0}

print(filtered_nums)

Output:

{24, 62, 14}

The structure of set comprehensions is similar to that of list and dictionary comprehensions:

{ expression for var in input if condition }

Generator Comprehensions in Python

Let’s take a look at generator comprehensions next. Similar to other comprehensions, generator comprehensions provide you with a shorthand for looping generators.

To demonstrate, let’s square even numbers in a list and leave out all the odd ones.

The for loop approach:

def square_even(numbers):
    for number in numbers:
        if number % 2 == 0:
            yield(number * number)

numbers = [1, 2, 3, 4, 5, 6]
squared_numbers = square_even(numbers)

for number in squared_numbers:
    print(number)

Output:

4
16
36

This works fine.

But with generator comprehensions, you can ditch square_even() method altogether and use a simple one-liner instead:

squared_numbers = (num * num for num in numbers if num % 2 == 0)

for number in squared_numbers: 
    print(number)

Output:

4
16
36

The basic structure for a generator comprehension is:

( expression for var in input if condition )

Awesome!

Now you have learned all the most common use cases of for loops in Python.

In this guide, we have been tossing around the word iterable without giving an explanation as to what it really is.

In the next chapter, we are going to take a deeper dive into the world of for loops and iterables in Python.

If you are a beginner, you do not need to worry about this stuff. However, it can still be beneficial to read it through.

To proceed, you need to understand double-underscore methods, while loops, and the basics of error handling!

Iterables & Iterators: How Do For Loops Work Under the Hood?

As you learned earlier in this chapter, you can loop through iterables in Python.

But what is it that makes an object iterable?

An iterable object implements the __iter__ method. This method returns an iterator object. This iterator object is then used to loop through the iterable.

The goal of this section is to make sense of the above definition.

Let’s start with the __iter__() method.

To qualify as an iterable, the object must implement a special method called __iter__().

For example, let’s inspect what methods a Python list object implements. To do this, you can create a list object and call the dir() function on it:

numbers = [1,2,3,4,5]
print(dir(numbers))

Output:

A long list of methods an iterable has

As you can see in the output, there is a method called __iter__ in the list.

This suggests that a list is indeed an iterable object.

As we stated in the definition, the __iter__() method must return an iterator object.

In Python, an iterator object is an object with a state. It knows the current element in the iterable. It also knows how to get the next one.

An iterator is characterized by a special method __next__(). When you call this method, the iterator object gives you the next element in the iterable.

To make any sense of this, let’s see an example where we:

  1. Create a list of numbers.
  2. Grab the iterator object of the list using the __iter__() method.
  3. Call the __next__() method on the iterator.

Here is how it looks in code:

# 1. Create a list
numbers = [1, 2, 3, 4, 5]

# 2. Grab the iterator
numbersIterator = numbers.__iter__()

# 3. Call the __next__() mehtod and show the result
print(numbersIterator.__next__())

Output:

1

The output is 1.

This is because the iterator object starts at the first element of the list.

Now, let’s call the __next__() method a bunch of times more:

print(numbersIterator.__next__())
print(numbersIterator.__next__())
print(numbersIterator.__next__())
print(numbersIterator.__next__())

Output:

2
3
4
5

The iterator object remembers what was the last element and continues from there. In this case, it successfully goes through all the numbers in the list.

Now, let’s see what happens if we call the __next__() for the 6th time:

print(numbersIterator.__next__())

Output:

Traceback (most recent call last):
  File "<string>", line 13, in <module>
StopIteration

Because there are no more values in the list, a StopIteration exception is thrown. At this point, the iterator is exhausted.

A for loop calls the iterator’s __next__() method to access the next item.

But why did I show you all of this?

Because this is how a for loop works under the hood.

A for loop calls the __iter__() method of the iterable to access the iterator. Then it calls the __next__() method on the iterator until there are no values left.

We can actually simulate how a for loop works using a while loop:

# 1. Create a list
numbers = [1, 2, 3, 4, 5]

# 2. Grab the iterator
numbersIterator = numbers.__iter__()

# 3. Ask the iterator for next values until no values left
while True:
    try:
        print(numbersIterator.__next__())
    except StopIteration:
        break

Output:

1
2
3
4
5

This piece of code is equivalent to this:

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)

Output:

1
2
3
4
5

Conclusion

In this guide, you learned what is a for loop in Python.

To recap, a for loop allows you to iterate over a collection of values.

This is useful in Python and in programming in general because there is a lot of data you need to handle.

In Python, any object that is iterable can be looped through using a for loop.

Iterable objects include:

  • Lists
  • Strings
  • Dictionaries
  • Tuples
  • Sets

All of these can be looped through using a for loop.

Thanks for reading.

Happy coding!

See Also