For Loop Examples in Python

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.

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

In this guide, you are going to see some common for loop examples in Python.

Print Each Element of a List

Let’s print a list of strings to separate lines.

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 a sequence of characters you can loop through.

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

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 a string that says “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.

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 a list of animal names and skip the “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

It is a common necessity to be able to easily create an iterable sequence of numbers. To do this, you can use the built-in range() function.

What is cool about the range() function is that it returns a range object that is an iterable object you can loop through.

For example:

for x in range(5):
  print(x)

Output:

1
2
3
4

With the range() function it is possible to define both the starting value and the ending value:

for x in range(2, 5):
   print(x)

Output:

2
3
4

You can even define the step size in the range. By default, it is 1, but you can change it to 20 for example:

for x in range(0, 100, 20):
  print(x)

Output:

0
20
40
60
80

Else Statement in a For Loop

You can place an else block at the end of a loop to run a piece of code as the loop terminates:

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

Output:

0
1
2
It's over

Nested For Loops in Python

In Python, you can add a loop inside a loop. This is called a nested loop.

For example:

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. You are always required to specify something that should happen in the loop.

If there is nothing you want to do in the loop, for now, you can use the pass statement.

For instance:

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

Now you can run this piece of code without the errors you would see without the pass statement.

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:

Each type of comprehension is 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]

Dictionary Comprehensions in Python

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

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 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 just 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 )

Conclusion

Today you saw some for loop examples in Python. I hope you find them useful.

Thanks for reading.

Happy coding!

See Also

10+ Python tricks and tips

50 Python Interview Questions

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.