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
Explore ChatGPT's 2025 memory updates: how it works, benefits, control options, and privacy insight
Discover why technical management continues to play a critical role in today's AI-powered workspaces. Learn how human leadership complements artificial intelligence in modern development teams
Not sure how to trust a language model? Learn how to evaluate LLMs for accuracy, reasoning, and task performance—without falling for the hype
Learn to boost PyTorch with custom kernels, exploring speed gains, risks, and balanced optimization for lasting performance
How interacting with remote databases works when using PostgreSQL and DBAPIs. Understand connection setup, query handling, security, and performance best practices for a smooth experience
How NVIDIA’s Neuralangelo is redefining 3D video reconstruction by converting ordinary 2D videos into detailed, interactive 3D models using advanced AI
What prompt engineering is, why it matters, and how to write effective AI prompts to get clear, accurate, and useful responses from language models
Why AI training is increasingly being shaped by tech giants instead of traditional schools. Explore how hands-on learning, tools, and real-time updates from major tech companies are changing the way people build careers in AI
Learn key strategies for prompt engineering to optimize AI language models and improve response accuracy and relevance
The ChatGPT iOS App now includes a 'Continue' button that makes it easier to resume incomplete responses, enhancing the flow of user interactions. Discover how this update improves daily usage
Discover how observability and AIOps transform IT operations with real-time insights, automation, and smart analytics.
How AWS S3 buckets and security work to keep your cloud data protected. This guide covers storage, permissions, encryption, and monitoring in simple terms