Advanced
Data Structures Algorithms & System Design(HLD+LLD)
by Logicmojo

Top tech companies experts provide live online training

Learn Data Structures, Algorithms & System Design

Online live classes from 4 to 7 months programs

Get job assistance after course completion

Download Course Brochure

Back to home
Logicmojo - Updated Sept 18, 2021



Statements are typically executed in order: the first statement in a function is executed first, then the second, and so on. You may find yourself in a position where you need to run a block of code multiple times.
Different control structures are available in programming languages, allowing for more sophisticated execution routes.
To meet looping requirements, the Python programming language supports the following types of loops. The loops can be executed in three different ways in Python. While all of the methods provide comparable basic functionality, they differ in syntax and the time it takes to check for conditions.

In this page we will discuss about Python For Loop in brief.


What do you mean by Python for Loop?

Iterating over a sequence is done with a for loop (that is either a list, a tuple, a dictionary, a set, or a string). This is more like an iterator method seen in other object-oriented programming languages than the for keyword in other programming languages.
The for loop allows us to run a sequence of statements once for each item in a list, tuple, set, or other data structure.

Syntax :

for iterator_var in sequence:
    statements(s)

On each iteration, iterator_var is the variable that takes the value of the item inside the sequence.
The loop will continue until the last item in the sequence is reached. Indentation is used to separate the body of the for loop from the remainder of the code.
It can be used to iterate across a set of iterators and a range of values.

Example Code :

animal = ["cat", "dog", "cow"]
for var in animal:
  print(var)

Output :

cat
dog
cow

There is no need to set an indexing variable before using the for loop.

Control statements in loops alter the execution sequence. All automatic objects generated in a scope are deleted when execution exits that scope.

The following control statements are supported by Python :
🚀 Break
🚀 Continue
🚀 Pass

How for loop works?

If you've ever done any programming, you've almost certainly encountered a for loop or something similar. Many programming languages provide conditions in their for loop syntax, such as a relational expression to decide whether the loop is complete and an increment expression to determine the next loop value. Instead, in Python, this is done by producing the proper sequence. A for loop can be used with any object that has an iterable method. Even strings, despite the lack of an iterable function - but more on that later. An iterable technique simply means that the data can be displayed in a list format, with many values arranged in a logical sequence.
By constructing an object using the next() and iter() methods, you can define your own iterables. This implies that when it comes to for loops in Python, you'll rarely be working with raw numbers, which is wonderful for just about everybody!


Break Statement in for Loop

We can break the loop before it loops over all of the objects by using the break statement:

Keyword :

break;

Example Code :

animal = ["cat", "dog", "cow"]
for var in animal:
    if var=="dog" :
        break
    print(var)

Output :

cat

The print statement will not be executed in the given example since the loop is broken by the break statement.


Continue Statement in for Loop

We can use the continue statement to end the current loop iteration and begin the next.

Keyword :

continue

Example Code :

animal = ["cat", "dog", "cow"]
for var in animal:
    if var=="dog" :
        continue
    print(var)

Output :

cat 
cow

The continue statement's purpose is to skip the current iteration of a loop and move on to the next one.

Pass Statement in for Loop

For loops cannot be empty, however if you have an empty for loop for some reason, use the pass statement to prevent an error.

Keyword :

pass

Example Code :

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

What is range() function?

The range() function can be used to create a numeric sequence. range(10) generates a range of values from 0 to 9. (10 numbers).
Range(start, stop, step size) can also be used to define the start, stop, and step size. If step size is not specified, it defaults to 1.
In some ways, the range object is "lazy" because it does not generate all of the numbers that it "contains" when we create it. It isn't an iterator, though, because it supports in, len, and __getitem__ actions.
Because it would be inefficient to save all of the values in memory, this function does not do so. As a result, it remembers the start, stop, and step size, as well as generating the next number on the fly.
We can use the function list to force this function to output all of the elements ().

Syntax :

range(start, stop, step size) 

🚀 The start indicates the start of the iteration.
🚀 The stop indicates that the loop will continue until it reaches stop-1. Iterations 1 to 4 will be generated by range(1,5). It's a choice.
🚀 The step size is used to skip the iteration's specific numbers. It's entirely up to you whether or not you want to use it. The step size is set at 1 by default. It's a choice.


Example 1 :

print(range(15))
print(list(range(15)))
print(list(range(2, 8)))
print(list(range(2, 15, 2)))

Output :

range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
[2, 3, 4, 5, 6, 7]
[2, 4, 6, 8, 10, 12, 14]


Example 2 :

n = 10
for i in range(1,11):  
x = n*i  
print(n,"*",i,"="x)  

Output :

10*1=10
10*2=20
10*3=30
10*4=40
10*5=50
10*6=60
10*7=70
10*8=80
10*9=90
10*10=100

With a sequence of numbers, we may utilise the range() method. The len() and range() functions are used to cycle across a sequence using indexing.
Let's understand this by taking an example,

Example :

list = ['Apple','Banana','Grapes','Pineapple'] 
for i in range(len(list)):
    print(list[i])  

Output :

Apple
Banana
Grapes
Pineapple

Using Else Statement in For Loop



Learn More

Unlike other programming languages such as C, C++, or Java, Python allows us to utilise the else statement with the for loop, which is only performed when all iterations have been completed. It's worth noting that the else statement will not be executed if the loop contains any break statements.
Python allows you to associate an else statement with a loop expression.
When the else statement is used with a for loop, it is performed after the loop has finished iterating the list.
The following example shows how to use an otherwise statement in conjunction with a for statement to find print "even" if numbers is even or "odd" if number is odd between 10 and 20.

Example :

for i in range(10,20):     
    if num%i == 0:         
        print("even");
    else:
        print("odd");

Output :

even
odd
even
odd
even
odd
even
odd
even
odd

Nested For loops

A nested loop is one that is contained within another loop.
For each iteration of the "outer loop," the "inner loop" will be run once.

You use a "nested loop" when you have a block of code that you want to run x number of times and then another block of code within that code that you want to execute y number of times. These are frequently used in Python when dealing with a list of lists - an iterable object within an iterable object.


Example : Pyramid Printing

n =  5
for i in range(0,n+1):  
     for j in range(i):  
        print(*,end = '')  
    print()  

Output :

*
* *
* * *
* * * *
* * * * *

Access Index in for Loop

AThe enumerate() method is used to iterate over the indices in a sequence.
The counter is added to iterable by the enumerate() function, which starts at 0 by default.


Example :

color = ['red', 'pink', 'blue', 'green']
for index, value in enumerate(color):  
    print(index, value)  

Output :

0 red
1 pink
2 blue
3 green

Use of For Loop Through Multiple Lists

We can iterate over numerous lists at the same time. The zip() function, which is integrated into the Python loop, is used for this.


Example :

from array import *
arr = arry(i, [10, 20, 30, 40, 50, 60])
for x in arr :
    print(x)  

Output :

10
20
30
40
50
60

Iterating by Sequence Index

Another method of iterating through each item is to use an index offset into the sequence. Here's a simple illustration:


Example :

fruits = ['apple', 'banana',  'mango', 'cheery']
for i in range(len(fruits)):
   print 'Fruit :', fruits[i]

print "Completed!"

Output :

Fruit : apple
Fruit : banana
Fruit : mango
Fruit : cheery
Completed !


The len() built-in function, which returns the total number of elements in the tuple, and the range() built-in function, which returns the actual sequence to iterate over, came in handy here.

Practice Problems using for loop

Let's see some problems that solved using for loop


Example 1. Iterate string using for loop in python

str = "LearnPython"  
for i in str:  
    print(i)  

Output :

L
e
a
r
n
P
y
t
h
o
n


Example 2. Program to print the table of the given number using list and for loop .

list = [1,2,3,4,5,6,7,8,9,10]  
n = 2  
for i in list:  
    num = n*i  
    print(num)

Output :

2
4
6
8
10
12
14
16
18
20


Example 3. Program to print sum of the elements of list

list = [1,2,3,4,5,6,7,8,9,10]  
sum = 0  
for i in list:  
    sum = sum + i  
print(sum)

Output :

55


Example 4. Program to print numbers in sequence.

for i n range(10):  
    print(i,end = ' ')  

Output :

1 2 3 4 5 6 7 8 9


Example 5. Program to print even number using step size in range().

for i in range(1,10,2):  
    print(i)  

Output :

1 3 5 7 9



The len() built-in function, which returns the total number of elements in the tuple, and the range() built-in function, which returns the actual sequence to iterate over, came in handy here.

Crack your next tech interview with confidence!

Conclusion

In this article, we looked at Python for loop and the many statements that it has. We also showed how to use the break, continue, and pass statements in a Python for loop with a visual example.