For Loops in Python

Meenakshi Agarwal
By
Meenakshi Agarwal
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large...
9 Min Read
Python for loop, syntax and examples

This tutorial explains Python for loop, and its syntax and provides various examples of iterating over different sequence data types. It is the most common control flow statement used by programmers for performing repetitive tasks. The best case to use it is when you know the total no. of iterations required for execution.

Python For Loop Definition, Syntax

Python provides a simple syntax for using “for loop” in programs. It can help you iterate through different types of objects. Python supports seven sequence data types: standard/Unicode strings, a list, tuples, a byte array, and xrange objects. There are sets and dictionaries as well, but they are just containers for the sequence types.

How to Use For Loops in Python

A for loop in Python requires at least two variables to work. The first is the iterable object such as a list, tuple, or string. And second, is the variable to store the successive values from the sequence in the loop.

Syntax

In Python, you can use the “for” loop in the following manner.

# syntax
for iter in sequence:
    statements(iter)

The “iter” represents the iterating variable. It gets assigned successive values from the input sequence.

The “sequence” may refer to any of the following Python objects such as a list, a tuple, or a string.

Flowchart

The for loop can include a single line or a block of code with multiple statements. Before executing the code inside the loop, the value from the sequence gets assigned to the iterating variable (“iter”).

Below is the For loop flowchart representation in Python:

Regular Python For Loop Flowchart
Regular Python For Loop Flowchart

Python For Loop Variations

You can apply a for loop to iterate through various data types in Python. Let’s check them out one by one.

Python for loop with a string

Here is the code to print all characters of a string.

# Program to print the letters of a string
vowels = "AEIOU"
for iter in vowels:
print("char:", iter)

""" Output
char: A
char: E
char: I
char: O
char: U
"""

Python for loop with a list

Here is a step-by-step procedure to calculate the average of N numbers in Python. We’ll use the following steps to compute the avg. of N numbers.

# Program to calculate the average of N integers
int_list = [1, 2, 3, 4, 5, 6]
sum = 0
for iter in int_list:
    sum += iter
print("Sum =", sum)
print("Avg =", sum/len(int_list))

Here is the output after executing the above code.

""" Output
Sum = 21
Avg = 3.5
"""

For loop with nested lists

The below code demonstrates how to print each element of a nested list in Python.

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

for row in matrix:
for element in row:
print(element, end=" ")
print()

For loop with range()

Python range() function returns a list or a sequence of numbers at runtime. For example, a statement like range(0, 10) will generate a series of ten integers starting from 0 to 9. The below snippet tries to show that range() returns a list and its elements are available via indexes.

# Check the type of list returned by range() function
print( type(range(0, 10)) )
# <class 'range'>

# Access first element in the range list 
print( range(0, 10)[0] )  # 0

# Access second element
print( range(0, 10)[1] )  # 1

# Access last element
print( range(0, 10)[9] )  # 9

# Caclulayte the size of range list
print( len(range(0, 10)) )  # 10

Let’s now use the range() with the loop.

for iter in range(0, 3):
    print("iter: %d" % (iter))

It will yield the following result.

""" Output
iter: 0
iter: 1
iter: 2
"""

By default, the for loop fetches elements from the sequence and assigns them to the iterating variable. But you can also make it return the index by replacing the sequence with a range(len(seq)) expression.

books = ['C', 'C++', 'Java', 'Python']
for index in range(len(books)):
   print('Book (%d):' % index, books[index])

The following lines will get printed.

""" Output
Book (0): C
Book (1): C++
Book (2): Java
Book (3): Python
"""

For loop with else clause

Interestingly, Python allows the use of an optional else statement along with the “for” loop.

The code under the else clause executes after the completion of the “for” loop. However, if the loop stops due to a “break” call, then it’ll skip the “else” clause.

Check the below syntax to use the else clause with the loop.

# Foe-Else Syntax

for item in seq:
    statement 1
    statement 2
    if <cond>:
        break
else:
    statements

Look at the below For Loop with Else flowchart to understand it more clearly.

Python for loop with else clause flowchart

Below is the sample code that uses a for loop and an else statement.

# Simple Python program to demonstrate the use of else with for loop
birds = ['Belle', 'Coco', 'Juniper', 'Lilly', 'Snow']
ignoreElse = False

for theBird in birds:
    print(theBird )
    if ignoreElse and theBird == 'Snow':
        break
else:
    print("No birds left.")

The above code will print the names of all birds plus the message in the “else” part.

Python for loop with enumerate

Here’s an example using a list of mixed data types:

mix = ["hello", 42, True, (1, 2), None]

for index, element in enumerate(mix):
print(f"Item {index + 1}: {element}")

Python for loop with a dictionary

Check how to iterate a dictionary in Python.

# A dictionary with mixed data types as keys
mix = {
"string": 123,
100: "value",
(1, 2): [True, False],
None: "null"
}

# Iterate over the dictionary using enumerate()
for index, (key, value) in enumerate(mix.items()):
print(f"Item {index + 1}: Key = {key}, Value = {value}")

Python for loops with zip()

A for loop with zip() lets you go through two or more lists together, pairing up the items in the same spot.

list1 = [1, 2, 3]
list2 = ["a", "b"]
for x, y in zip(list1, list2):
print(x, y) # Output: 1 a, 2 b

Nested for loops

Nested loops are like loops within loops. They help you go through items in a list of lists, one by one.

for i in range(5):
for j in range(3):
if i == 2 and j == 1:
break
print(i, j)

For loop with pass

A Python for loop with pass is like an empty loop that does nothing. It’s useful when you need the loop structure but don’t want to run any code inside it.

for num in range(10):
if num % 2 == 0:
continue # Skip even numbers
else:
pass # Do nothing for odd numbers
print(num)

For loop with break

A Python for loop with a break is like stopping a loop early. It’s useful when you want to exit the loop before it finishes all its rounds.

numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num > 3:
break
print(num)

For loop in one line

A Python for loop in one line is a quick way to do something for every item in a list. It’s like saying, “Do this thing for each item here.”

for num in range(10): print(f"Number {num}: {num ** 2}")

Before You Leave

In this tutorial, we explained the concept of Python for Loop with several examples so that you can easily use it in real-time Python programs. However, if you have any questions about this topic, please do write to us.

Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.

Happy Coding,
TechBeamers.

Share This Article
Leave a Comment

Leave a Reply

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