How to Use the For Loop in Python
Using a for loop in Python allows you to execute a block of code repeatedly over a sequence like a list, a tuple, or even a string. This is particularly useful when you want to perform an action with each item in a collection.
To start using a for loop, you need to follow these basic steps:
Identify the Sequence: First, determine what sequence you will loop through. This could be a range of numbers, elements in a list, characters in a string, or keys in a dictionary.
Write the For Loop: The syntax for a for loop is straightforward:
for item in sequence:
# code to execute for each item
Replace item with the name you want to give each element in the sequence, and sequence with the actual sequence you're looping through.
Add Code Inside the Loop: Inside the loop, you write the code that you want to execute for each item. This could be as simple as printing each item or more complex operations like calculations or processing data.
Here is an example of a for loop in Python that prints each number from 1 to 5:
for number in range(1, 6): # range(1, 6) generates numbers from 1 to 5
print(number)
This example will output:
1
2
3
4
5
The range() function is commonly used in for loops to generate a sequence of numbers. In the code above, range(1, 6) makes the loop run five times, printing each number from 1 to 5.
Python For Loop Syntax
The syntax of a for loop in Python is designed to be simple & effective, making it easy to loop through items in a sequence. Let's break down the syntax to understand how to write a for loop correctly.
Here's the basic structure of a for loop in Python:
for variable in iterable:
# Code to execute for each item
- variable: This is a placeholder that takes the value of each item in the sequence as the loop iterates through it. You can name it anything you like, but it should make sense in the context of your code.
- iterable: An iterable is any Python object capable of returning its members one at a time, allowing it to be iterated over in a for-loop. Common iterables include lists, tuples, dictionaries, sets, and strings.
- Code Block: This is the block of code that you want to repeat for each item in the iterable. It's indented under the for statement, and it runs once for every iteration of the loop.
Here's an example to illustrate the syntax:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(f'I like {fruit}')
In this example:
- fruit is the variable that takes each value from the fruits list.
- The fruits list is the iterable.
- print(f'I like {fruit}') is the code executed for each fruit, outputting statements like "I like apple", "I like banana", and "I like cherry".
Note -: This structure makes it easy to perform tasks on each item in a collection without manually accessing each item by index, improving code readability and efficiency.
Python For Loop with String
Using a for loop with strings in Python is an excellent way to perform operations on each character in the string. This approach is straightforward and very useful in various programming scenarios, such as counting specific characters or transforming string data.
Example :
Python
text = "hello"
for char in text:
print(char)

You can also try this code with Online Python Compiler
Run Code
In this example, the loop will iterate over the string text, which contains "hello". For each iteration, the variable char takes on the value of each character in the string, one by one.
The print(char) statement inside the loop block will output each character individually:
h
e
l
l
o
This method is particularly useful for tasks like:
- Counting characters: You can count how many times each character appears in a string.
- Modifying strings: You can build a new string or modify the existing one character by character.
- Checking strings: You can check for the presence of specific characters or patterns within the string.
Here's a more practical example, where we use a for loop to count the number of times the letter 'l' appears in the string:
text = "hello"
count = 0
for char in text:
if char == 'l':
count += 1
print(f"The letter 'l' appears {count} times in the word 'hello'.")
This code will correctly report that the letter 'l' appears 2 times in the word "hello".
Python For Loop with Integer
Using a for loop with integers in Python is a common practice for repeating a set of instructions a specific number of times. This is especially useful in scenarios where you need to execute code a predetermined number of times, such as performing calculations, generating sequences, or automating repetitive tasks.
Example :
for number in range(5):
print(number)
In this code:
- The range(5) function generates a sequence of integers from 0 to 4.
- The for loop iterates through this sequence, assigning each value to the variable number.
- The print(number) statement inside the loop block outputs each integer.
This results in the following output:
0
1
2
3
4
The range() function is incredibly versatile:
- range(stop): Generates numbers from 0 to stop-1.
- range(start, stop): Generates numbers from start to stop-1.
- range(start, stop, step): Generates numbers from start to stop-1, incrementing by step.
For example, to print even numbers between 0 and 10, you would use:
for number in range(0, 11, 2):
print(number)
This loop will print:
0
2
4
6
8
10
Python For Loop Enumerate
The enumerate() function in Python adds a counter to an iterable, making it easier to access both the index and the value during a for loop. This is particularly useful when you need both the item and its position in the iterable, such as when you're working with lists or strings and need to keep track of the items' positions for further processing.
Example :
Python
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f'{index}: {fruit}')

You can also try this code with Online Python Compiler
Run Code
In this example:
- enumerate(fruits) provides a sequence of pairs, each containing an index (starting from 0) and the value from the fruits list.
- index and fruit are the variables that get the index number and the fruit name, respectively.
- The print() function is used to display the index and the fruit.
The output of this code would be:
0: apple
1: banana
2: cherry
Using enumerate() is beneficial when:
- You need to replace items in a list while iterating.
- You want to display the index of items when showing them to users.
- You need to check the position of items when evaluating conditions.
Nested For Loops in Python
Nested for loops in Python are used when you need to perform operations on items that are themselves collections of other items. This concept is similar to having a loop inside another loop, allowing you to iterate over each element of a nested structure.
Example :
Python
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for num in row:
print(num, end=' ')
print() # for a new line after each row

You can also try this code with Online Python Compiler
Run Code
In this example:
- The outer loop iterates over each list (each row in the matrix).
- The inner loop iterates over each number in the current row list.
- print(num, end=' ') prints each number followed by a space instead of a new line.
- print() without arguments prints a newline, ensuring each row of numbers appears on a new line.
The output for the code above will be:
1 2 3
4 5 6
7 8 9
Nested loops are particularly useful for:
- Working with multi-dimensional data structures like matrices.
- Performing operations that require accessing elements in a grid-like format, such as in games, data analysis, or graphical applications.
- Complex data processing tasks where each item of a main collection contains multiple sub-items that need individual processing.
Python For Loop with List
A for loop with a list in Python allows you to execute a block of code for each item in the list. This is one of the most common and practical uses of for loops in Python, as lists are versatile and widely used data structures that can store various types of data.
Example :
Python
names = ['Rahul', 'Harsh', 'Mehak', 'Gaurav']
for name in names:
print(f"Hello, {name}!")

You can also try this code with Online Python Compiler
Run Code
In this example:
- The list names contains several strings, each representing a name.
- The for loop iterates over each element in the names list.
- The print(f"Hello, {name}!") statement within the loop generates a personalized greeting for each name in the list.
The output of this code would be:
Hello, Rahul!
Hello, Harsh!
Hello, Mehak!
Hello, Gaurav!
Using a for loop with lists is beneficial for:
- Processing or transforming all items in a list.
- Generating output based on the items in a list.
- Collecting data from users or other sources into a list and then iterating through it to perform operations.
Python For Loop with Dictionary
For loops with dictionaries in Python enable you to iterate over each key-value pair in the dictionary. This functionality is extremely useful for accessing and manipulating dictionary data, which is a common data structure for storing data pairs.
Example :
Python
student_grades = {'Rekha': 88, 'Rohan': 76, 'Sinki': 94, 'Rinki': 82}
for name, grade in student_grades.items():
print(f"{name} scored {grade}% on the exam.")

You can also try this code with Online Python Compiler
Run Code
In this example:
- student_grades is a dictionary containing names as keys and grades as values.
- .items() is a method that returns a view object displaying a list of a dictionary's key-value tuple pairs.
- name and grade are variables that each key and value from the dictionary are assigned to during each iteration.
- The print() function is used to display a message that includes both the name and the corresponding grade.
The output will be:
Rekha scored 88% on the exam.
Rohan scored 76% on the exam.
Sinki scored 94% on the exam.
Rinki scored 82% on the exam.
Using for loops with dictionaries allows for:
- Easy extraction and manipulation of data stored in key-value format.
- Efficient processing of data for tasks such as data analysis, data reporting, or even conditional operations based on specific criteria.
Note -: This method of iteration is essential for handling dictionary data in Python, facilitating straightforward and readable code for complex data operations.
Python For Loop with Tuple
Using a for loop with a tuple in Python is similar to using it with a list or a dictionary, allowing you to iterate over each element in the tuple. Tuples are immutable, meaning they cannot be changed after creation, making them useful for storing data that should not be modified.
Example :
Python
colors = ('red', 'green', 'blue')
for color in colors:
print(f"The color is {color}.")

You can also try this code with Online Python Compiler
Run Code
In this example:
- colors is a tuple containing three elements: 'red', 'green', and 'blue'.
- Each iteration of the loop assigns one element from the tuple to the variable color.
- The print() function is used to display a message about each color.
The output of this code will be:
The color is red.
The color is green.
The color is blue.
Using a for loop with tuples is beneficial for:
- Iterating through data that should not change, ensuring data integrity.
- Accessing each element of the tuple clearly and straightforwardly.
- Performing operations or calculations using the data stored in tuples.
Note -: Since tuples are less flexible than lists (because they cannot be altered after creation), they are typically used in situations where a constant set of values is needed throughout a program.
Python For Loop with Zip()
The zip() function in Python is a powerful tool when used with a for loop, allowing you to iterate over multiple sequences (like lists, tuples) simultaneously. This function makes it easy to combine several iterables and loop through them concurrently, which is useful for tasks that involve correlating data from different sources.
Example :
Python
names = ['Akash', 'Gaurav', 'Abhishek']
scores = [85, 90, 95]
for name, score in zip(names, scores):
print(f"{name} scored {score}")

You can also try this code with Online Python Compiler
Run Code
In this example:
- names and scores are two lists that we want to combine for processing.
- zip(names, scores) pairs each element of the first list with the corresponding element in the second list.
- Each iteration of the loop extracts one paired element from the zip object, assigning them to name and score.
- The print() function outputs a formatted string showing each name with the corresponding score.
The output will be:
Akash scored 85
Gaurav scored 90
Abhishek scored 95
Using zip() in a for loop is particularly useful for:
- Comparing or combining elements from different sequences in a concise manner.
- Performing operations that require elements from multiple lists to be processed together, such as data merging, comparison, or creating new derived lists.
Control Statements that can be used with the For Loops in Python
Control statements within for loops in Python enhance the flexibility and efficiency of loops by directing the flow of execution. These include break, continue, and pass statements, each serving a unique purpose to manage loop operations effectively.
1. break Statement
The break statement immediately terminates a loop entirely. It is typically used to exit a loop when a specific condition is met.
Example:
for number in range(1, 11):
if number == 5:
break
print(number)
This loop will print numbers from 1 to 4. When the number reaches 5, the break statement stops the loop entirely.
2. continue Statement:
The continue statement skips the current iteration of the loop and moves to the next iteration. This is used when you want to skip certain elements or conditions within a loop.
Example:
for number in range(1, 11):
if number % 2 == 0:
continue
print(number)
This loop prints only odd numbers between 1 and 10. It skips even numbers because the continue statement moves the loop to the next iteration whenever an even number is encountered.
3. pass Statement
The pass statement acts as a placeholder and does nothing. It is used when syntax requires a statement but no action needs to be taken.
Example:
for number in range(1, 11):
if number % 2 == 0:
pass # We do nothing for even numbers
else:
print(number)
This loop checks if numbers are even but only acts (prints the number) if they are odd.
Frequently Asked Questions
Can a for loop be used for all types of iterables in Python?
Yes, for loops in Python can be used with any iterable object, such as lists, tuples, dictionaries, strings, and sets. They are versatile and allow you to execute a block of code for each item in the iterable.
What happens if I modify an iterable while iterating over it in a for loop?
Modifying an iterable while iterating over it can lead to unexpected behavior or errors. It is generally recommended to avoid changing the size of the iterable (like adding or removing elements) during iteration.
How can I loop through two lists at once?
You can loop through two lists simultaneously by using the zip() function, which pairs elements from two or more lists together. This allows you to use a single for loop to access paired elements from each list concurrently.
Conclusion
In this article, we have learned about the versatile Python for loop and talked about its syntax and practical applications with various data types like strings, integers, lists, dictionaries, and tuples. We've also discussed how to use the enumerate() and zip() functions to enhance loop functionality and discussed essential control statements like break, continue, and pass that control the flow within loops.