Start Your Journey with Linux Command Line
![]() |
| for loop |
In Python, the for loop is an essential tool for automation. It allows you to execute a block of code repeatedly for every item in a sequence—whether that’s a list of names, a range of numbers, or rows in a database.
Before we look at the code, let's break down the syntax:
As seen in our initial example, range(5) is a common way to generate a sequence:
for x in range(5):
print(x)
Output: 0, 1, 2, 3, 4
Key Takeaway:Python is zero-indexed. This means range(5) starts at 0 and stops before 5. It generates five numbers in total, but the last number is always N-1.
The true power of a for loop shines when you use it to handle real data. Since for loops can iterate over any "iterable" object, they are perfect for processing collections.
Imagine you have a list of users or technologies you are working with:
tech_stack = ["Python", "Django", "Excel", "PowerBI"]
for tool in tech_stack:
print(f"I am processing data using {tool}")
You can even loop through a single word to inspect every character:
for letter in "Python":
print(letter.upper())
One of the most common questions is: "Which loop should I choose?"
If you need both the item and its position (index) in the list, use enumerate(). This is incredibly helpful when building reports or tracking task positions:
tasks = ["Clean Data", "Run Analysis", "Upload to VPS"]
for index, task in enumerate(tasks, start=1):
print(f"Task {index}: {task}")
One powerful pattern is using range() with two arguments to iterate over a subset of a list by index. For example, for i in range(1, len(my_list)) starts from the second element, which is useful when you need to compare each element with the one before it. You can also step through a sequence by a fixed amount using the third argument of range(), such as range(0, 20, 3) which yields 0, 3, 6, 9, 12, 15, 18.
When iterating over dictionaries, you can loop through keys with for key in my_dict, through values with for value in my_dict.values(), or through key-value pairs with for key, value in my_dict.items(). The items() approach is especially handy when you need both the label and the data in each iteration.
Avoid modifying a list while iterating over it, as this can cause elements to be skipped or produce unexpected results. If you need to filter items, build a new list with a list comprehension or use filter() instead of removing elements in place during the loop.
for loop iterates over every item in a sequence such as a list, tuple, string, or the output of range().range(start, stop, step) to control the beginning, end, and increment of numeric iterations..keys(), .values(), and .items().break exits the loop early while continue skips to the next iteration without finishing the current block.else clause after a for loop runs only if the loop completes without hitting a break statement.You cannot pass a plain integer directly to a for loop. You must wrap it in range() first. For example, for i in range(5) works, but for i in 5 raises a TypeError.
Use the built-in enumerate() function. Writing for index, value in enumerate(my_list) gives you both the position and the element in each iteration without manually managing a counter.
Yes. Nesting a for loop inside another is common when working with 2D data such as lists of lists or matrices. The inner loop completes all its iterations for each single iteration of the outer loop.
A for loop is best when you know the exact sequence or number of iterations in advance. A while loop runs as long as a condition remains true and is better suited for situations where the number of iterations depends on a dynamic condition rather than a fixed collection.
The for loop is the backbone of efficient Python programming. It reduces manual work, prevents code repetition, and makes your scripts more readable.
Try it yourself: Can you write a loop that calculates the sum of numbers from 1 to 10?
LEt us know in the comments, or, make a post in our Facebook Page or Group.
Comments
Post a Comment
Your opinion matters, your voice makes us proud and happy. Your words are our motivation.