Browse Tutorials
Python For Loop

Python For Loop

29 Mar 2024
Beginner
138 Views
12 min read
Learn via Video Course & by Doing Hands-on Labs

Python Programming For Beginners Free Course

Python for Loop: An Overview

In the previous Python tutorial, Types of Loops in Python, we saw the types of loops in Python. In this tutorial, we'll understand the first loop, i.e., Python for loop, in detail. Just remain with us till the end and you will be thorough with the Python for Loop.

What is a for loop in Python?

The Python for loop is different from the for loop used in other programming languages like C, C++, and Java. The for loop in Python is a Collection-Based or Iterator-Based Loop. This type of loop iterates over a collection of objects rather than specifying numeric values or conditions. With the Python for loop, we can execute a set of statements, once for each item in a list, tuple, set, dictionary, string, etc.

Python for loop Syntax


for var in iterable/sequence:
    # statements      

Here, the variable, "var" accesses each item of the sequence/iterable on each iteration. The loop continues until we reach the last item in the sequence.

Flowchart of Python for loop

Flow chart of python of loop

Examples of Python For Loop

In this section, we will see the demonstration of the Python for loop for all the sequence types.

1. Python For Loop with List


list = ["Welcome", "to", "ScholarHat"] 

for i in list: 
	print(i) 
        

The above Python code in the Python Compiler uses a for loop to iterate over a list of strings, printing each item in the list on a new line.

Output

Welcome
to
ScholarHat      

2. Python For Loop in Python Dictionary


print("Dictionary Iteration") 
  
d = dict() 
  
d['abc'] = 567
d['xyz'] = 456
for i in d: 
    print("% s % d" % (i, d[i]))
        

The above Python code uses a for loop to iterate over a dictionary and print each key-value pair on a new line.

Output

Dictionary Iteration
abc  567
xyz  456    

3. Python For Loop in Python String


print("String Iteration") 

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

This code uses in the Python Editor a for loop to iterate over a string and print each character on a new line.

Output

String Iteration
S
c
h
o
l
a
r
H
a
t      

4. Python For Loop with Tuple


t = ((1, 2), (9, 10), (15, 16)) 
for a, b in t: 
	print(a, b) 
        

In each iteration, the values from the inner tuple are assigned to variables a and b, respectively, and then printed to the console using the print() function.

Output

1 2
9 10
15 16        

Altering Python for Loop Behavior with Loop Control Statements

We have learned that loop control statements are used to alter the regular flow of a loop. They enable you to skip iterations, end the loop early, or do nothing at all. Let's see the demonstration of all three loop control statements in Python with Python for loop.

1. Python for Loop with Continue Statement

The continue Statement in Python returns the control to the beginning of the loop.


for letter in 'ScholarHat': 

	if letter == 'h' or letter == 'a': 
		continue
	print('Current Letter :', letter) 
 

Output

Current Letter : S
Current Letter : c
Current Letter : o
Current Letter : l
Current Letter : r
Current Letter : H
Current Letter : t

2. Python for Loop with Break Statement

The break statement in Python brings control out of the loop. It terminates the loop completely and proceeds to the first statement following the loop.


for letter in 'ScholarHat': 

	if letter == 'H'or letter == 'a': 
		break

print('Current Letter :', letter) 
 

Output

Current Letter : a

3. Python for Loop with Pass Statement

The pass statement in Python is used to write empty loops. Pass is also used for empty control statements, functions, and classes.


for letter in 'ScholarHat': 
	pass
print('last Letter :', letter) 
 

Output

last Letter : t

4. for Loop with Python range()

The Python range() function returns a sequence of numbers. It takes mainly three arguments:

  1. start: integer starting from which the sequence of integers is to be returned
  2. stop: integer before which the sequence of integers is to be returned. The range of integers ends at a stop – 1.
  3. step: integer value which determines the increment between each integer in the sequence.

We know that the for loop in Python iterates over a collection of objects or sequences. Hence, we can iterate over the range() function using a for loop.


for i in range(10):
    print(i)
 

The code works accordingly:

IterationValue of iprint(i)Last item in sequence?
1st0Prints 0No
2nd1Prints 1No
3rd2Prints 2No
4th3Prints 3No
5th4Prints 4No
6th5Prints 5No
7th6Prints 6No
8th7Prints 7No
9th8Prints 8No
10th9Prints 9No

Output

0
1
2
3
4
5
6
7
8
9 

Using else Statement with for Loop in Python

A Python for loop can have an optional else clause. This else clause executes after the iteration completes.

Example of Python Loop program in Python Online Compiler with else Statement with for Loop in Python


numbers = [12, 13, 14]

for i in numbers:
    print(i)
else:
    print("No numbers left.")
 

In the above code, the for loop prints all the items of the numbers list. When the loop finishes, it executes the else block.

Output

12
13
14
No numbers left.

Remember: The else clause won’t be executed if the list is broken out with a break statement.

Example


for x in range(7):
  if x == 5: break
  print(x)
else:
  print("Finally finished!")
 

Here, there is a break statement that executes when x becomes 5. Hence, the control comes out of the for loop without the execution of the else statement.

Output

0
1
2
3
4 
Summary

In this tutorial, we looked at the for loop in Python programming. We covered the for loop with all the aspects necessary to understand it completely. The illustrations given above will provide you with a good level of clarity on the various parts of the main topic.

Share Article
Batches Schedule
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this