Advertisement
When you're just getting started with Python, loops can seem like one of those things that everyone else just magically "gets." The good news is, they’re not as mysterious as they seem. For loops, in particular, are a handy tool for repeating actions without writing the same line of code over and over again. They help you move through lists, strings ranges—basically anything that can be counted or broken down, one item at a time.
This guide walks you through how Python’s for loop works with examples that you can actually use. No fluff, no abstract theory—just the ways you'll likely use for loops in real code.
Lists show up everywhere in Python, and looping through them is one of the first useful tricks you’ll pick up. Take this list of fruits:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Here, Python handles the heavy lifting—grabbing each item and printing it, with no counters or extra effort needed from you.
If you just want to do something five times or loop through numbers from 0 to 9, range() is the way to go.
for i in range(5):
print(i)
Output:
0
1
2
3
4
range(5) gives you numbers from 0 to 4. If you want to start somewhere else, you can add a second argument.
for i in range(2, 6):
print(i)
Output:
2
3
4
5
You can even add a step:
for i in range(0, 10, 2):
print(i)
Output:
0
2
4
6
8
Strings are just sequences of characters, so you can loop through them the same way you would loop through a list.
word = "hello"
for letter in word:
print(letter)
Output:
h
e
l
l
o
Each character is treated as a separate item in the loop.
If you need both the value and the index (position) of each item in a list, enumerate() gives you that easily.
names = ['Tom', 'Jerry', 'Spike']
for index, name in enumerate(names):
print(f"{index}: {name}")
Output:
0: Tom
1: Jerry
2: Spike
No need to manage a counter manually—enumerate() does it for you.
Dictionaries hold key-value pairs. If you loop through them directly, you get the keys.
person = {'name': 'Alice', 'age': 30}
for key in person:
print(key)
Output:
name
age
To get both keys and values:
for key, value in person.items():
print(f"{key}: {value}")
Output:
name: Alice
age: 30
A nested loop is just a loop inside another loop. This is useful for working with lists of lists, tables or grids.
matrix = [
[1, 2],
[3, 4],
[5, 6]
]
for row in the matrix:
for item in row:
print(item)
Output:
1
2
3
4
5
6
Each row is a list itself. The inner loop goes through each item in that row.
Sometimes, you want to exit the loop early or skip part of it. That’s where break and continue come in.
break: Exit the loop if a condition is met.
for num in range(10):
if num == 5:
break
print(num)
Output:
0
1
2
3
4
continue: Skip the current iteration and go to the next one.
for num in range(5):
if num == 2:
continue
print(num)
Output:
0
1
3
4
If you just want to build a new list from an existing one, list comprehensions let you write the loop in a single line.
squares = [x * x for x in range(5)]
print(squares)
Output:
[0, 1, 4, 9, 16]
You can even add conditions:
even_squares = [x * x for x in range(10) if x % 2 == 0]
print(even_squares)
Output:
[0, 4, 16, 36, 64]
This is just a compact way of doing a loop and building a list at the same time.
When you have two lists of related items, such as names and scores, you can loop through both simultaneously using zip(). It pairs up the items in order.
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
Output:
Alice scored 85
Bob scored 92
Charlie scored 78
If the lists are of different lengths, zip() stops at the shortest one. This is helpful when you're dealing with data from two sources that you know are aligned.
If you want to keep going with the longest list and fill in missing values, you can use itertools.zip_longest() from the standard library.
from itertools import zip_longest
names = ['Alice', 'Bob']
scores = [85, 92, 78]
for name, score in zip_longest(names, scores, fillvalue='N/A'):
print(f"{name} scored {score}")
Output:
Alice scored 85
Bob scored 92
N/A scored 78
When working with files, you can use a for loop to read each line without loading the entire file into memory.
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
This method is memory-efficient, especially for large files. The loop reads one line at a time. Using strip() removes the newline character at the end of each line. It’s a clean way to process logs, data files, or any text-based content stored on disk.
Python’s for loop is one of the simplest and most useful tools you'll use regularly. It helps you go through lists, strings, ranges, and even dictionaries with ease. Whether you're looping with indexes, using conditions, or working with multiple lists, there’s a clean way to do it. With just a bit of practice, writing loops becomes second nature. The examples above cover the most common patterns you'll run into. Try modifying them or combining ideas to fit your tasks. The more you work with loops, the more natural they'll feel—and the clearer your code will become.
Advertisement
Compare Power BI vs Tableau in 2025 to find out which BI tool suits your business better. Explore ease of use, pricing, performance, and visual features in this detailed guide
Explore ChatGPT's 2025 memory updates: how it works, benefits, control options, and privacy insight
Explore how AI enhances employee performance, learning, and engagement across today's fast-changing workplace environments.
Discover seven powerful ways AI helps manage uncertainty and improve resilience in today's fast-changing business world.
Explore how AI is transforming drug discovery by speeding up development and improving treatment success rates.
How NVIDIA’s Neuralangelo is redefining 3D video reconstruction by converting ordinary 2D videos into detailed, interactive 3D models using advanced AI
Discover AI’s latest surprises, innovations, and big wins transforming industries and everyday life.
How to use a Python For Loop with easy-to-follow examples. This beginner-friendly guide walks you through practical ways to write clean, effective loops in Python
Explore how AI is boosting cybersecurity with smarter threat detection and faster response to cyber attacks
Discover how 9 big tech firms are boldly shaping generative AI trends, innovative tools, and the latest industry news.
Domino Data Lab joins Nvidia and NetApp to make managing AI projects easier, faster, and more productive for businesses
AI tools for solo businesses, best AI tools 2025, AI for small business, one-person business tools, AI productivity tools