For Loop Examples in Python

In Python, a for loop is used for iterating over a sequence (a list, a tuple, a dictionary, a set, or a string). Using the for loop you can execute statements, once for each item in the sequence. In this guide, you will see the common for loop examples in Python.

Print Each Element of a List

This is the most basic for loop example in Python. Print each element of the list using a for loop.

For example, let’s print a list of animals:

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

for animal in animals:
  print(animal)

Output:

monkey
lion
elephant

Loop Through Characters of a String

In Python, strings are iterable objects. In other words, a string is just a sequence of characters you can loop through.

For example:

for x in "apple":
  print(x)

Output:

a
p
p
l
e

Break the Loop

Sometimes you need to break the loop. In other words, you want to escape the loop altogether and move on in the program execution.

For example, let’s escape the for loop if we encounter an elephant:

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

Continue Statement in Python

Sometimes you want to skip the “rest of the current iteration” and continue to the next iteration in a loop. This is possible by using the continue keyword.

For example, let’s loop through animals and skip printing lion using continue:

animals = ["monkey", "lion", "elephant"]
 
for animal in animals:
    if animal == "lion":
       continue
    print(animal)

Output:

monkey
elephant

For Loops and the range() Function

Create a range of numbers over which you iterate using the range() function. It returns a sequence of numbers, starting from 0 by default, and increments by 1 by default, and ends at the specified number excluding it.

For example:

# Prints 0, 1, 2, 3, 4
for x in range(5):
  print(x)

You can also specify both the starting and the ending value:

# Prints 2, 3, 4
for x in range(2, 5):
   print(x)

You can even define what the interval should be. By default, it is 1, but you can change it to 20 for example:

# Prints 0, 20, 40 ,60, 80
for x in range(0, 100, 20):
  print(x)

Else Statement in a For Loop

You can place an else block at the end of a loop to do something when the loop execution finishes:

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

Output:

0
1
2
It's over

A Loop Inside a Loop—Nested For Loops in Python

A loop or multiple loops inside a loop is called a nested loop in Python. For instance:

adjectives = ["small", "big"]
animals = ["monkey", "viper", "fly"]

for adjecitve in adjectives:
  for animal in animals:
    print(adjecitve, animal)

Output:

small monkey
small viper
small fly
big monkey
big viper
big fly

How to Create an Empty For Loop

You may have noticed you can’t leave a for loop empty. But if you for some reason need to leave the for loop empty, use the pass keyword:

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

One-Liner For Loops

So now that you’ve seen some common for loop examples in Python, it is time to see how to make your code readable by introducing a one-liner for loops. These are useful when you are creating a new sequence from an existing one, so you’re not necessarily repeating the above examples.

In Python, most of the time you can turn your regular for loops into one-liners by using comprehensions.

Python supports four different types of comprehensions:

  • List comprehensions
  • Dictionary comprehensions
  • Set comprehensions
  • Generator comprehensions

These are pretty similar to one another. Let’s see some examples.

List Comprehensions in Python

Let’s create a list of numbers based on an existing list by leaving all the negative numbers out. You can use a for loop to solve this task:

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]

But you can make the loop shorter and more readable by using a list comprehension like this:

new_nums = [num for num in numbers if num > 0]
print(new_nums)

Output:

[4, 7, 19]

Here is the general structure of the list comprehension:

output_list = [expression for var in input_list if condition]

The if condition is optional. For example, consider squaring the numbers list using list comprehension:

squares = [num * num for num in numbers]

Dictionary Comprehensions in Python

Python has a shorthand for looping through dictionaries too. This is known as dictionary comprehension.

Basically, there are two use cases for dictionary comprehensions in Python:

  1. Turn an iterable, such as a list, into a dictionary.
  2. Operate on an existing dictionary.

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

Say you want to create a dictionary from 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:

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. 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'}

2. Example—How to Operate on an Existing Dictionary Using Dictionary Comprehensions

Let’s see another example where you square the number values of the dictionary and create a new dictionary of it:

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. No readability was sacrificed in this process either.

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 the for loop version:

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 things become simpler:

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 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 is cool. But with generator comprehensions, you can forget the square_even method altogether and use the one-liner approach:

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 )

Conclusion

Thanks for reading! I hope you find it useful and learned something new.

Further Reading

10+ Python tricks and tips

50 Python Interview Questions

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest

Leave a Comment

Your email address will not be published. Required fields are marked *