How do you execute a simple for loop in Python?

Key takeaways:

  • Python’s for loop simplifies iteration by allowing traversal over sequences like lists, tuples, strings, and dictionaries without requiring explicit indexing.

  • for loops support various functionality such as using range(), handling control statements (break, continue, pass), and iterating over multiple sequences using zip().

  • for loop enhance code readability and efficiency, making it a fundamental tool for automating repetitive tasks and working with structured data.

for loop

In Python, a for loop iterates over the elements of a sequence (that is, either a list, a tuple, a dictionary, a set, or a string) using an iterating variable that keeps track of the current item in the sequence. This allows a piece of code to be executed repeatedly for each element of the sequence.

The for loop does not require an indexing variable to be set beforehand.

Syntax in Python

The basic syntax is given below:

for variable in sequence:
# Code to execute for each element
Basic syntax
  • variable: This is the variable that will take the value of each element in the sequence, one by one.

  • sequence: The collection of items you want to loop through (like a list, string, tuple, etc.).

  • The indented block of code under the for loop is executed for each element in the sequence.

Flow diagram

Here is a high-level flowchart of a for-loop:

Flow diagram
Flow diagram

Example 1: iterating through a list

This example demonstrates how to iterate over a list using a for loop. The list clothes contains three elements: “hat,” “shirt,” and “pant.” The loop assigns each element to the variable item one at a time and prints it. This approach is helpful for processing elements in a sequence without using indexes.

clothes = ["hat", "shirt", "pant"]
for item in clothes:
print(item)

Example 2: using range() with a for Loop

In the following code, the range(5) function generates a sequence of numbers starting from 0 up to (but not including) 5. The for loop iterates through this sequence, assigning each number to the variable i and printing it.

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

Example 3: looping through a string

Strings in Python are iterable, meaning you can loop through each character individually. In the following example, the string "Hello" is treated as a sequence of characters. The for loop assigns each character to the variable char and prints it. This is useful for tasks like analyzing or modifying text character by character.

message = "Hello"
for char in message:
print(char)

Example 4: using the for loop with dictionaries

Dictionaries store data as key-value pairs, and the items() method provides both the key and the value for each pair. This example uses a for loop to iterate through the dictionary student. For each iteration, the loop assigns the key to the variable key and the value to the variable value. It then prints both, formatted as “key: value.” This technique is useful for iterating over data structures that map one value to another, such as JSON objects or configuration settings.

student = {"name": "John", "age": 20, "grade": "A"}
for key, value in student.items():
print(f"{key}: {value}")

Example 5: using control statements inside for loops

Control statements like break, continue, and pass can be used inside a for loop to modify its behavior.

1. break statement

The break statement is used to exit the loop prematurely when a certain condition is met. When break is executed, the loop stops, and the program continues with the next statement after the loop.

for number in range(10):
if number == 5:
break # Exits the loop when number equals 5
print(number)

2. continue statement

The continue statement is used to skip the current iteration and move on to the next iteration. It is often used when you want to skip certain conditions while continuing the loop.

for number in range(5):
if number == 2:
continue # Skips printing 2
print(number)

3. pass statement

The pass statement is a placeholder that allows the loop to continue without doing anything. It is useful when a block of code is syntactically required but doesn’t need to perform any action.

for number in range(3):
if number == 1:
pass # Does nothing when number equals 1
print(number)

Example 6: nested for loops

Nested for loops allow you to iterate over multi-dimensional data structures such as lists of lists, matrices, or combinations of multiple iterables.

for i in range(3):
for j in range(3):
print(f"i = {i}, j = {j}")

Example 7: using enumerate() in for loops

The enumerate() function is used when you need both the index and the value of items in an iterable. It returns an iterator that generates pairs of index and element. enumerate() is particularly useful when you need to know the index of the current item while iterating through a sequence, avoiding the need to manually manage the index with an additional variable.

clothes = ["hat", "shirt", "pant"]
for index, cloth in enumerate(clothes):
print(f"Index {index}: {cloth}")

Example 8: using else in for loops

In Python, you can use the else block with a for loop. The code inside the else block will execute only when the loop finishes normally (i.e., not interrupted by a break statement).

for number in range(5):
print(number)
else:
print("Loop completed without interruption.")

Example 9: using for loops with tuples

A tuple is an ordered collection of elements, much like a list, but unlike lists, tuples are immutable. You can use a for loop to iterate through the elements of a tuple just as you would with other iterables like lists.

clothes = ("hat", "shirt", "pant")
for cloth in clothes:
print(cloth)

Example 10: using for loop with zip()

The zip() function is a powerful tool in Python that combines multiple iterables into a single iterable of tuples. Each tuple contains elements from the corresponding position in the input iterables. When used with a for loop, zip() allows you to iterate over two or more iterables simultaneously.

names = ["Car A", "Car B", "Car C"]
price = [90, 80, 85]
for name, score in zip(names, price):
print(f"{name}: {score}")

Learn the basics with our engaging course!

Start your coding journey with the “Learn Python” course—the perfect course for absolute beginners! Whether you’re exploring coding as a hobby or building a foundation for a tech career, this course is your gateway to mastering Python—the most beginner-friendly and in-demand programming language. With simple explanations, interactive exercises, and real-world examples, you’ll confidently write your first programs and understand Python essentials. Our step-by-step approach ensures you grasp core concepts while having fun along the way. Join now and start your Python journey today—no prior experience is required!

Conclusion

Python’s for loop provides an intuitive and powerful way to iterate over sequences without the need for explicit indexing. Its simplicity and efficiency make it an essential tool for automating repetitive tasks and enhancing code readability.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How is the `for` loop executed in Python?

  • Iteration: The for loop is designed to iterate over any iterable object, including lists, tuples, strings, and ranges.
  • Assignment: In each iteration, the loop variable is assigned the current element from the sequence.
  • Execution: The code block within the loop (indented) is executed with the current value of the loop variable.
  • Next element: The loop proceeds to the next element in the sequence and repeats the process.
  • Termination: The loop continues until all elements in the sequence have been processed.

How to make a simple loop in Python?

We can make a simple loop in Python in the following way:

for i in range(5): 
    print(i) 
  • This loop will print the numbers 0 to 4.
  • range(5) creates a sequence of numbers from 0 to 4.
  • i is the loop variable that takes on each value in the sequence.

How does a `for` loop execute?

  1. Initialization: The for loop starts by obtaining the first element from the sequence.
  2. Condition check: The loop checks if there are more elements in the sequence.
  3. Body execution: If there are more elements, the code within the loop is executed with the current element assigned to the loop variable.
  4. Iteration: The loop moves to the next element in the sequence.
  5. Repetition: Steps 2–4 are repeated until all elements in the sequence have been processed.

How do you run a Python code in a loop?

You can run Python code in a loop using two commonly used loops: for loop or a while loop.

Using a for loop:
for i in range(5):  
    print("Hello, World!")  

(Prints “Hello, World!” five times.)

Using a while loop:
count = 0  
while count < 5:  
    print("Hello, World!")  
    count += 1  

(Runs until count reaches 5.)


What is the syntax of a `for` loop in Python?

The basic syntax of a for loop in Python is:

for variable in iterable:
    # Code block to execute

Example:

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

Output:

0  
1  
2  
3  
4  

Here, range(5) generates numbers from 0 to 4, and the loop iterates over them.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved