How to Use For Loops in Python with Solved Examples

Advertisement

Jun 07, 2025 By Alison Perry

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.

How to Use For Loops in Python?

Looping Through a List

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.

Using range() to Loop a Specific Number of Times

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

Looping Through a String

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.

Looping with Index Using enumerate()

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.

Looping Through a Dictionary

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

Nested For Loops

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.

Using break and continue

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

List Comprehension with For Loop

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.

Looping Through Two Lists at the Same Time with zip()

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

Looping Over Files Line by Line

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.

Conclusion

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

You May Like

Top

What’s the Better BI Tool in 2025: Tableau or Power BI

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

Jun 07, 2025
Read
Top

What ChatGPT's Memory Update Means for You

Explore ChatGPT's 2025 memory updates: how it works, benefits, control options, and privacy insight

Jul 01, 2025
Read
Top

Discover How AI Empowers Employees in the Modern Workplace

Explore how AI enhances employee performance, learning, and engagement across today's fast-changing workplace environments.

Jul 02, 2025
Read
Top

Top 7 Ways to Use AI for Uncertainty Management

Discover seven powerful ways AI helps manage uncertainty and improve resilience in today's fast-changing business world.

Jul 02, 2025
Read
Top

Adopting AI in Drug Discovery: A New Era in Medicine

Explore how AI is transforming drug discovery by speeding up development and improving treatment success rates.

Jul 02, 2025
Read
Top

How Neuralangelo by NVIDIA Turns Simple Videos into Realistic 3D Models

How NVIDIA’s Neuralangelo is redefining 3D video reconstruction by converting ordinary 2D videos into detailed, interactive 3D models using advanced AI

Jun 08, 2025
Read
Top

AI Innovations and Big Wins You Should Know About

Discover AI’s latest surprises, innovations, and big wins transforming industries and everyday life.

Jul 02, 2025
Read
Top

How to Use For Loops in Python with Solved Examples

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

Jun 07, 2025
Read
Top

How Artificial Intelligence Is Strengthening Cybersecurity

Explore how AI is boosting cybersecurity with smarter threat detection and faster response to cyber attacks

Jul 02, 2025
Read
Top

Discover the Role of 9 Big Tech Firms in Generative AI News

Discover how 9 big tech firms are boldly shaping generative AI trends, innovative tools, and the latest industry news.

Jun 26, 2025
Read
Top

Domino Data Lab: Best AI Software for Data Management

Domino Data Lab joins Nvidia and NetApp to make managing AI projects easier, faster, and more productive for businesses

Jun 25, 2025
Read
Top

Which AI Tools Can Boost Solo Businesses in 2025?

AI tools for solo businesses, best AI tools 2025, AI for small business, one-person business tools, AI productivity tools

Jul 01, 2025
Read