In Python, a for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
Unlike the for keyword in other programming languages, Python's for loop works more like an iterator method found in object-oriented programming languages. It executes a block of code for each item in the sequence.
Initialization: The loop takes a sequence (like a list or a range).
Assignment: In each iteration, the next value in the sequence is assigned to a "loop variable."
Execution: The indented code block is executed with that variable.
Termination: The loop continues until it reaches the end of the sequence.
To loop through a set of code a specified number of times, we use the range() function.
range(5): Generates numbers from 0 to 4 (5 is not included).
range(2, 6): Generates numbers from 2 to 5.
range(2, 30, 3): Generates numbers from 2 to 29, incrementing by 3.
A string is an iterable object; it contains a sequence of characters.
word = "PYTHON" for letter in word: print(f"Current Character: {letter}")
This is the most common way to run a loop a specific number of times.
# Print numbers 1 to 5 for i in range(1, 6): print(f"Iteration Number: {i}")
fruits = ["Apple", "Banana", "Cherry"] for fruit in fruits: print(f"I like eating {fruit}")
The else keyword in a for loop specifies a block of code to be executed when the loop is finished. Note: The else block will NOT be executed if the loop is stopped by a break statement.
for x in range(3): print(x) else: print("Loop finished successfully!")
A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop".
colors = ["red", "big", "tasty"] fruits = ["apple", "banana"] for x in colors: for y in fruits: print(x, y)
| Benefit | Description |
| Automation | Performs repetitive tasks without manual coding for each step. |
| Data Processing | Easily traverses through data structures like Lists and Dictionaries. |
| Efficiency | Reduces the number of lines in your code, making it cleaner and easier to debug. |
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION