Python for Loop: In Programming, there are different types of loop available.

However, In Python, you can make use of 2 loops only: for Loop and while Loop.

In this article, we are going to take a deep look at Python for Loop, it’s working, and all the important topics related to for Loop with examples.

As we know that loop is used for traversing over the sequence.

Similarly, for Loop is used for iterating over the sequence, range, string, list, tuple, dictionary, and other objects.

We will discuss all these topics one by one in this tutorial.

So, let’s start with the basic syntax of Python for Loop.

Table of Contents

Syntax of Python for Loop

As you know that for Loop is used for iterating over the fixed and limited sequence of the element.

So, for defining a for Loop, you need a sequence of elements on which you will perform the repetitive iteration.

The syntax of for Loop is as follow:

				
					
for VARIABLE in SEQUENCE:
    STATEMENTS #body of For Loop
				
			

As you can see in the above syntax, firstly we specified a “for” keyword followed by the iterator variable (VARIABLE) which is used for temporarily storing the value of the sequence elements iteratively.

After that, we have used the “in” keyword followed by that a sequence or set of elements (string, range, list, tuple dictionary) is defined, which has to be iterated, and then we have used the : (colon) symbol.

for VARIABLE in SEQUENCE:

In the next line, we have used the indentation for creating a block of code inside the for Loop.

So, after the indentation, we can define the statements or set of code that has to be executed every time a for Loop iterates.

Now, let’s take a look at some of the self-explanatory examples of for Loop which will give you a much better understanding.

Python for Loop Examples

Here are some of the simple examples of Python for Loop:

1. Python for Loop with string

				
					
for str in "CODING":
    print(str)
				
			

Output:
C
O
D
I
N
G

2. Python for Loop with list

				
					languages = ["English", "Hindi", "Germany", "French"]

for i in languages:
    print(i)
				
			

Output:
English
Hindi
Germany
French

3. Python for Loop with range()

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

Output:
0
1
2
3
4

4. Python for Loop with sequence

				
					list = [5, 9, 1, 3, 7]

for i in range(len(list)):
    print(list[i])
				
			

Output:
5
9
1
3
7

Now, that you have seen some of the basic examples of Python for Loop. It’s time to move to the next concept which is Iteration in for Loop.

Iteration in Python for Loop

Let’s take a look at some of the examples of iteration in for Loop with explanation:

1. Iterating through a range() Function

In Python, range() is a function that is used for returning the sequence of elements.

There are 3 types of arguments you can pass in range function.

Let’s start with the first type of argument in range() in which you can use a single argument only.

When we use range() with a single argument, it returns the elements from 0 to (argument – 1).

For example – range(4) will return 0, 1, 2, 3.

Now here is the example of range() function having a single argument with for Loop.

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

Output:
0
1
2
3
4

So, you can see that we get the value from 0 to 4 as an output of the above code.

Now, let’s take a look at another type of range() function which takes 2 arguments.

The first argument is the starting index and the second argument is the ending index.

So, it returns the sequence of elements between the first argument and the second argument of the range function.

For example – range(3, 7) will return 3, 4, 5, 6 as a result.

Below is the example of range() having 2 arguments in the for Loop.

				
					
for var in range(3, 9):
    print(var)
				
			

Output:
3
4
5
6
7
8

As a result of the above code, we get the values starting from 3 till 8 (excluding the last value which is 9).

With this, we get to the 3rd and last type of range() function which takes 3 arguments (Starting, Ending, Steps).

It is similar to the second type of range() which we have discussed above.

However, the only difference is that here we have used the step argument as well.

The step argument is used for specifying the number of sequences we have to skip during the iteration.

For example – range(1, 8, 3) will return 1, 4, 7. This is because here range() function is iterated between 1 to 8 and skipped 3 steps after every iteration.

				
					
for var in range(4, 20, 2):
    print(var)
				
			

Output:
4
6
8
10
12
14
16
18

Similarly, In the above example, you can see that the range function is iterated between 4 to 20 and has skipped 2 steps after every iteration.

2. Iterating by Sequence Index

Now moving towards our next type of iteration in for Loop which is Iteration by Sequence Index.

Iterating by Sequence Index is a very common practice and is used in other Programming Languages as well.

If you are a C++ Programmer, then you know that index operator ( [ ] ) are used for accessing or printing the elements of an array.

Similarly, here also you can use the index operator for accessing the elements of the sequence.

So, below is the example of iteration by sequence index in for Loop.

				
					list1 = [2, 4, 6, 8, 10, 12]

for x in range(len(list1)):
    print(list1[x])
				
			

Output:
2
4
6
8
10
12

In the above program, we have also used len() function for getting the length of the list (which is 6).

Then the range() function used this length for returning the sequence of elements (which is 0, 1, 2, 3, 4, 5).

This sequence is iterated by for Loop and one by one gets stored in the iterator variable (which is x).

At last inside the for Loop body, you can print the list element using this iterator variable and index operator.

Below is another example of the Iteration by Sequence Index in for Loop.

				
					list2 = ['Java', 'Python', 'JavaScript', 'C++', 'Swift']

for x in range(len(list2)):
    print(list2[x])
				
			

Output:
Java
Python
JavaScript
C++
Swift

The above code is similar to the previous one. However, the only difference is that instead of numbers, here we have used the string in the list.

3. Iterating over String

A string is a sequence of characters that can be iterated with the help of for Loop.

In Python, you can iterate over every character of the string very easily.

Below is the simple example of iteration over string in Python.

				
					string = "CODERPEDIA"

for i in string:
    print(i)
				
			

Output:
C
O
D
E
R
P
E
D
I
A

As you can see that we have firstly initialized a variable with the string “CODERPEDIA”.

Then this string or sequence of characters has been iterated with the help of for Loop.

With every iteration, it prints the character of that string.

Below is another variation of iteration over a string.

				
					
for i in "PROGRAMMER":
    print(i)
				
			

Output:
P
R
O
G
R
A
M
M
E
R

Here, instead of initializing the string in a variable and then using that variable in the for Loop, we have directly used the string in our for Loop, which is also a better approach.

4. Iterating over List

The list is one of the most important data structures in Python. It is used for storing the sequence of elements and is mutable.

This means that the elements of the list can be changed directly.

With for Loop, you can iterate over a list very easily.

Below is the example of iteration performed over a list.

				
					list1 = [3, 6, 9, 12, 15]

for x in list1:
    print(x)
				
			

Output:
3
6
9
12
15

As you can see that we have directly iterated over the sequence of elements inside the list.

Similarly, you can perform iteration with the help of an index operator as well.

				
					list2 = [4, 8, 12, 16, 20, 24]

for x in range(len(list2)):
    print(list2[x])
				
			

Output:
4
8
12
16
20
24

All you need is a length of a list and the range function which will give us the sequence of values from 0 to (length_of_list – 1).

for Loop can also be used for inserting the elements inside the list.

Let’s understand this with the help of an example.

				
					number = []

for n in range(5):
    number.append(n)

print(number)
				
			

Output:
[0, 1, 2, 3, 4]

To insert the elements in the list, we make use of append() in python.

So, with the help of the append function, we have iteratively inserted the numbers from 0 to 4 inside our list.

There is another alternative approach for inserting the elements in the list, which is List Comprehension.

We also have a dedicated article on List Comprehension in Python, which you must take a look at.

5. Iterating over Tuple

In Python, tuples are similar to the list. However, unlike a list, tuples are created with Parenthesis and they are immutable.

This means that the elements of the tuple cannot be changed.

The syntax for iterating over a tuple is very similar to the iteration over a list.

				
					city = ("London", "Dubai", "Paris", "Tokyo")

for x in city:
    print(x)
				
			

Output:
London
Dubai
Paris
Tokyo

6. Iterating over List of Tuples

In Python, you can also combine the 2 different data types, which are list and tuple.

Using tuples inside the list will give us a new data type which is “List of Tuples“.

So, a List of Tuples can also be iterated with the help of for Loop very easily.

Below is the simple example of iteration over a List of Tuples.

				
					marks = [("English", 78), ("Computer", 85), ("Economics", 65), ("Science", 72), ("French", 56)]

for x in marks:
    print(x[0], x[1])
				
			

Output:
English 78
Computer 85
Economics 65
Science 72
French 56

As you can see that we have used marks (which is a List of Tuple) as a sequence in the for Loop.

Each tuple is an element inside the list and with every iteration, you can access these tuples.

In the above example, x is an iterator variable which temporarily holds the value of tuple iteratively.

Now, for printing the values of the tuple, we have used the index operator ( [] ).

Index 0 will give us the first value of the tuple and index 1 will give us the second value of the tuple.

Like this, we can print every element inside the List of Tuples.

7. Iterating over Dictionary

Dictionary is another important data structure that is used for storing the key-value pairs.

So, like other data structures, a dictionary can also be used as a sequence in for Loop.

For example – In the below code, we have initialized a dictionary named “capitalsOfcountry”, which consists of Country as a key and Capital as a value.

				
					capitalsOfcountry = {
            'Egypt' : 'Cairo',
            'France' : 'Paris',
            'Germany' : 'Berlin',
            'India' : 'New Delhi',
            'Japan' : 'Tokyo'
          }

for country in capitalsOfcountry:
    print(country)
				
			

Output:
Egypt
France
Germany
India
Japan

As you can see, In the above code, we have used a dictionary in the for Loop and an iterator variable named “country”.

This variable temporarily holds the key part of the dictionary iteratively.

As a result, we get the name of countries in the output.

However, if you want to print the value part of the dictionary, then in the sequence, you have to use the dictionary name followed by values() function in the for Loop.

For example – As you can see in the below code, we have used the capitalsOfcountry.values() as a sequence, which gives us the sequence of all the value part of the dictionary named “capitalsOfcountry”.

				
					capitalsOfcountry = {
            'Egypt' : 'Cairo',
            'France' : 'Paris',
            'Germany' : 'Berlin',
            'India' : 'New Delhi',
            'Japan' : 'Tokyo'
          }

for capital in capitalsOfcountry.values():
    print(capital)
				
			

Output:
Cairo
Paris
Berlin
New Delhi
Tokyo

Now let’s take a look at another example of iteration over Dictionary, in which we will print the key as well as the value part of the dictionary.

				
					capitalsOfcountry = {
            'Egypt' : 'Cairo',
            'France' : 'Paris',
            'Germany' : 'Berlin',
            'India' : 'New Delhi',
            'Japan' : 'Tokyo'
          }

for country, capital in capitalsOfcountry.items():
    print(country, ":", capital)
				
			

Output:
Egypt : Cairo
France : Paris
Germany : Berlin
India : New Delhi
Japan : Tokyo

As you can see that in the above code, we have used capitalsOfcountry.item() as a sequence, which will return the key as well as the value of the dictionary.

To store these key and value, we will use 2 iterator variables (country and capital).

So, sequentially country variable will hold the key part and the capital variable will hold the value part.

Nested for Loop in Python

You can use one for Loop inside another for Loop as well.

As you can see that in the below code, we have used for Loop having range(4, 7) inside the another for Loop having range(1, 3).

				
					
for i in range(1, 3):
    for j in range(4, 7):
        print(i, j)
				
			

Output:
1 4
1 5
1 6
2 4
2 5
2 6

As a result, firstly the outer for Loop with range(1, 3) gets called and then the inner for Loop having range(4, 7) gets called iteratively.

Best Course

-> Best Course for learning Python: Python for Everybody Specialization

break, continue and pass statement in For Loop

In Python, you can use 3 types of statement for controlling the flow of Loop conditions, which are break, continue, and pass statement.

So, firstly let’s take a look at the break statement with for Loop.

1. break statement

The break statement is used for breaking or terminating the loop.

Let’s understand the working of the break statement inside the for Loop with a simple example.

				
					
for str in 'CODERPEDIA':
    if str == 'P':
        break

    else:
        print(str)
				
			

Output:
C
O
D
E
R

As you can see in the above code that we have performed iteration over a string.

So, inside the for Loop body, we have used the if condition in which if str variable will get equals to ‘P’, the program will get terminated, and otherwise the value of str will get printed on the screen.

As a result, we get “CODER” in our output screen.

2. continue statement

The continue is another statement which you can use for controlling the flow of Loop.

The continue statement works the same as the break statement do.

However, unlike the break statement, the continue statement just skips that particular iteration and moves the flow of the program to the next iteration.

For example – As you can see in the below code, we have used the continue statement inside the for Loop.

				
					
for str in 'CODERPEDIA':
    if str == 'P':
        continue

    else:
        print(str)
				
			

Output:
C
O
D
E
R
E
D
I
A

In the above code, if str will get equals to ‘P’, the continue statement will get called and as a result, this particular iteration will get skipped and ‘P’ will not get printed on the screen and we will get “CODEREDIA” as an output.

3. pass statement

The pass statement is also known as a NULL statement. It does nothing but is used as a placeholder for future code.

If you want to use some code inside the Loop or Function body but you don’t have that particular code at present.

Then one option is to leave that Loop or Function body empty. However, it will through an error as well.

Another option and the most preferred one is to make use of the pass statement.

If you will just type “pass” inside the body of the Loop or Function statement, it will do nothing and will not show any error as well.

				
					
for str in 'CODERPEDIA':
    if str == 'P':
        pass
        print("Here is a Pass Block")
    print(str)
				
			

Output:
C
O
D
E
R
Here is a Pass Block
P
E
D
I
A

As you can see in the above code, we typed pass inside the if statement, and nothing happens to our code.

Else Statement in Python for Loop

Python also provides us the out-of-the-box features which not many programming languages provide.

For example – You can use else statement with for Loop.

Now you might be thinking that what is the use of else statement with for Loop.

In Python, else statement with for Loop is used in case you want to perform any operation after the execution of for Loop.

So, else statement will get executed after the execution of for Loop.

				
					for x in range(1, 4):
    print(x)
else:
    print("Else Statement in For Loop")
print("Loop Ends")
				
			

Output:
1
2
3
Else Statement in For Loop
Loop Ends

As you can see in the above program, firstly the for Loop prints the value from 1 to 3 and after the termination of the loop, else block gets executed.

Hope you like the article on Python for Loop. We also have an article on Lambda Function in Python, which you must take a look at.

This Post Has One Comment

  1. Paulks

    Thanks the lesson is practical and straightforward.

Leave a Reply