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:
1 2 3 |
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.
Working of Nested for Loops
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.
1 2 3 4 |
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.
1 2 3 4 5 |
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 "
.
1 |
S a c h i n R i s h u Y a s h w a n t |
Example of Nested for Loops
1 2 3 4 5 6 7 |
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
“.
1 2 3 4 5 6 |
Sachin plays Cricket Sachin plays Snooker Rishu plays Cricket Rishu plays Snooker Yashwant plays Cricket Yashwant plays Snooker |
Nested for Loops with range() Function
1 2 3 4 |
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)
.
1 2 3 |
0 0 1 |
Application of Nested for Loops in Real World
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.
Example – Tokenizing Sentence into Words and Characters
1 2 3 4 5 6 7 8 9 10 11 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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) |
Conclusion
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 a 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ββ