Python For Loop: Syntax, Examples & Best Practice

Python For Loop: Syntax, Examples & Best Practice

03 Jul 2025
Beginner
4.13K Views
15 min read
Learn with an interactive course and practical hands-on labs

Free Python Programming Course For Beginners

The for loop in Python is a control flow statement used to repeat a block of code for a fixed number of times. It is commonly used to iterate over sequences like lists, strings, tuples, or ranges. The for loop in Python makes it easy to go through each item one by one and perform actions. Whether you're processing data or automating tasks, the for loop in Python is one of the most useful tools for beginners and advanced users alike.

In the Python tutorial, you'll learn how the for loop in Python works and how to use it with lists, strings, and more.

What is a for loop in Python?

For loop in Python is a control flow statement designed to iterate over a sequence, like a list, tuple, string, or range, and other iterable objects. It repeatedly executes a block of code for every item in the sequence.

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 demonstrate the Python for loop for all 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        

Changing 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: starting value from which he sequence begins (it is inclusive and default is 0)
  2. stop: ending value up to which the number is generated ( it is exclusive and always required)
  3. step: increment after generating an integer (it is optional and default is 1)

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 :

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 

Nesting Python for loops

When we use a for loop inside another for loop, then it is called a nested for loop. There are many application for nested for loops. Some of them are:
  • Iteration through 2D-Arrays
  • Generating combinations
  • Creating patterns
  • Sorting and searching algorithms

Example:


matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
for row in matrix:
    for element in row:
        print(element, end=" ")
    print() # Move to the next line after each row

Using Enumerate with a for loop

The enumerate function is used in Python to iterate over an iterable while also keeping track of the index of each item.

Example:


seasons = ['Spring', 'Summer', 'Fall', 'Winter']
for index, season in enumerate(seasons):
    print(f'Index: {index}, Season: {season}')


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. If you further want to increase your knowledge in Python, join our Full Stack Python Developer Certification Training

FAQs

A for loop in Python is a control structure that allows you to repeat a block of code for each item in a sequence, such as a list, string, tuple, dictionary, or any iterable object. It helps automate repetitive tasks without needing to write the same code multiple times.

Use a for loop when you know beforehand how many times you want the loop to run or when you are looping through a fixed set of items. A while loop is better when the number of iterations depends on a condition that is evaluated during execution.

If the sequence provided to the for loop is empty, the loop body will not execute at all. The program will simply skip the loop and continue with the next lines of code.

Yes, a for loop can have an else clause that runs only if the loop finishes normally—meaning it was not exited prematurely using a break statement. This feature is often used to handle situations where something should happen only if the loop didn't encounter an early exit.

Yes, Python allows you to stop a for loop early by using control statements. The most common way to do this is by using a break statement, which immediately exits the loop when a certain condition is met.

Take our Python skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
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.

Live Training - Book Free Demo
Azure AI Engineer Certification Training
17 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Accept cookies & close this