Nested for Loops in Python - How to Use Them

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.
Search for a command to run...

I am a self-taught Python developer who loves to write on Python Programming and quite obsessed with Machine Learning.
No comments yet. Be the first to comment.
When you’re building an application, one thing you can’t skip is API testing. Whether it’s a login flow, payment gateway, or a complex e-commerce workflow, ensuring your APIs behave correctly saves you from nasty surprises in production. I had alread...

PyPy is an implementation of Python written in RPython (Reduced Python) language, and it is seen as a replacement for CPython. PyPy claims that it is almost a drop-in replacement for CPython and can beat it on speed and memory usage. It supports libr...

You must have used functions provided by the os module in Python several times in your projects. These could be used to create a file, walk down a directory, get info on the current directory, perform path operations, and more. In this article, we’ll...

FastAPI is a fast and modern web framework known for its support for asynchronous REST API and ease of use. In this article, we’ll see how to stream videos on frontend in FastAPI. StreamingResponse Stream Local Video FastAPI provides a StreamingRespo...

Have you ever come across circular imports in Python? Well, it’s a very common code smell that indicates something’s wrong with the design or structure. Circular Import Example How does circular import occur? This import error usually occurs when two...
You may have used Python for loops to iterate through iterable objects in order to access them independently and perform various operations. You're probably familiar with the concept of nested for loops as well.
In Python, nested for loops are loops that have one or more for loops within them.
Nested for loops have a structure that is similar to the following code:
for x in my_iterable:
for item in x:
print(item.upper())
You may have seen the use of nested for loops in the creation of various patterns of asterisk or hyphen symbols.
A nested for loop is made up of both an outer loop and an inner loop. When observing the structure of the nested for loop mentioned earlier, you'll observe that the initial part of the code represents an outer for loop, and within this outer for loop, there exists an inner for loop.
for anything in article: # Outer for-loop
# Some code here
for everything in anything: # Inner for-loop
# Some code here
But how they go hand in hand and iterate through data. Let's uncover the iteration process of nested for loops.
my_iterable = ["Sachin", "Rishu", "Yashwant"]
for item in my_iterable:
for each_elem in item:
print(each_elem, end=" ")
The outer loop accesses each item in my_iterable.
For each item in the outer loop (e.g., "Sachin"), the inner loop iterates through each individual element in the item (e.g., "S", "a", "c", "h", "i", "n").
The print statement prints each character with a space, producing output like "S a c h i n ".
S a c h i n R i s h u Y a s h w a n t
names = ["Sachin", "Rishu", "Yashwant"]
games = ["Cricket", "Snooker"]
for item in names: # Outer loop
for game in games: # Inner loop
print(item, "plays", game)
The outer loop iterates through the names list (Sachin, Rishu, Yashwant).
For each name in the outer loop, the inner loop iterates through the games list (Cricket, Snooker).
The print statement combines the current name with each game to output sentences like "Sachin plays Cricket" and "Sachin plays Snooker".
Sachin plays Cricket
Sachin plays Snooker
Rishu plays Cricket
Rishu plays Snooker
Yashwant plays Cricket
Yashwant plays Snooker
for i in range(1, 2):
for x in range(3):
for num in range(x):
print(num)
The above code might be a bit confusing, let's break it down into pieces:
The outer for loop (for i in range(1, 2)) executes once because the range is from 1 to 2 (not inclusive), resulting in a single iteration. This loop governs the number of times the inner loops are executed.
The middle or inner for loop runs three times because of the range from 0 to 2. The iterations produce the values 0, 1, and 2.
The innermost for loop's behavior depends on the middle for loop because its range relies on the current value of the x variable.
When the value of x is 0 (first iteration), the innermost loop won't execute because the range is empty. When the value of x is 1 (second iteration), it runs for one time returning the value 0 due to the range(1), and then finally when x is 2 (third iteration), it runs two times returning the values 0 and 1 due to the range(2).
0
0
1
There are various ways to use nested for loops. They come in handy when you need to perform multiple rounds of iterations, deal with layered data structures like lists inside dictionaries or lists within other lists for navigating through data, or when you want to process and analyze text by breaking it down into smaller parts.
text = "Hey, there! Welcome to GeekPython."
sentences = text.split(". ") # Splitting the text into sentences
print("Tokenized Sentences into Words and Characters:")
for sentence in sentences:
print("- Sentence:", sentence)
words = sentence.split(" ") # Splitting sentence into words
for word in words:
print(" - Word:", word)
for character in word:
print(" - Character:", character)
The above code tokenizes (breaking sentences into small units) the text data into words and characters using the nested for loops. The code goes as follows:
The text data is initially split into sentences using text.split(". "), where the period followed by a space is used as the delimiter.
The outer for loop iterates through sentences and prints them. The current sentence is then split into words using sentence.split(" ").
Then subsequent for loop iterates through the words of the current sentence and prints them.
Additionally, a further nested for loop is nested within the word loop, which processes the characters within each word, one at a time.
The inner for loops are executed for every cycle of the outer for loop. This signifies that the code's process is repeated for each sentence. However, since the provided code only deals with one sentence, it executes just once.
Tokenized Sentences into Words and Characters:
- Sentence: Hey, there! Welcome to GeekPython.
- Word: Hey,
- Character: H
- Character: e
- Character: y
- Character: ,
- Word: there!
- Character: t
- Character: h
- Character: e
- Character: r
- Character: e
- Character: !
- Word: Welcome
- Character: W
- Character: e
- Character: l
- Character: c
- Character: o
- Character: m
- Character: e
- Word: to
- Character: t
- Character: o
- Word: GeekPython.
- Character: G
- Character: e
- Character: e
- Character: k
- Character: P
- Character: y
- Character: t
- Character: h
- Character: o
- Character: n
- Character: .
You could have also performed the tokenization of textual data by reading the data from the file and to do so, you just need to adjust your code as shown below:
with open("test.txt") as file:
content = file.read()
sentences = content.split(". ")
print("Tokenized sentences into words and characters:")
for sentence in sentences:
print("- Sentence:", sentence)
words = sentence.split(" ")
for word in words:
print(" - Word:", word)
for char in word:
print(" - Character:", char)
Python's for loops are employed to sequentially go through a series of data elements, allowing access to each of them individually. Furthermore, a single for loop can contain one or more additional for loops within it, a concept commonly known as nested for loops.
In the context of nested for loops, during every iteration of the outer for loop, the inner for loop iterates through each item present in the respective iterable. To illustrate, consider the scenario of shopping: envision visiting various shops and inspecting the items they offer. You start by exploring the first shop, examining all its items, and then proceed to the next shop, repeating this process until you have surveyed all available shops.
Let's recall what you've learned:
What are nested for loops in Python
How nested for loops work
Code examples of nested for loops
🏆Other articles you might be interested in if you liked this one
âś…How to display messages using flash() in Flask app?
âś…How to structure Flask app using Blueprint?
âś…Upload and display images on the frontend using Flask in Python.
âś…Change string representation of the objects using __str__ and __repr__.
âś…How to connect the SQLite database with the Flask app using Python?
âś…How to implement __getitem__, __setitem__ and __delitem__ in Python?
That's all for now
Keep Coding✌✌