Textlogo_codingem_white

Programming tips for everyone

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 most common for loop examples in Python with brief explanations.

Print Each Animal in the List

This is the most basic for loop use case in Python. Print a list of elements:

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 x in "apple":
  print(x)

Output:

a
p
p
l
e


Break the Loop

Sometimes you may need to break the loop at some point in order not to continue looping for nothing:

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 to the Next Iteration

Sometimes you may want to skip the rest of the loop and continue to the next iteration using the continue keyword. For example, let’s loop through animals and skip printing lion:

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

Output:

monkey
elephant


For Loops and 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 in 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

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


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 For Prettier Code

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

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

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

Create a dictionary from a list

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 number:

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



Operate on an existing dictionary

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

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

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

So that’s it. A useful list of for loop examples in Python. I hope you find it useful and learned something new.



You May Also Like

10 Useful Python Tricks

Python JSON Pretty Print

Formatted String in Python

Share on facebook
Share on twitter
Share on linkedin

Related Articles

Artturi Jalli

Technical Writer

Entrepreneur, Software Engineer, Mobile App Dev, MSc Physics Student, And Tech Enthusiast from Finland

artturi@codingem.com

My Personal Favorites
Sponsor

Buy an Online Course

Lorem ipsum dolor sit amet consectetur adipiscing elit dolor
Explore Categories

Favorites