You are currently viewing Understanding Nested for Loops in Python – How Does it Work

Understanding Nested for Loops in Python – How Does it Work

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:

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.

But how they go hand in hand and iterate through data. Let’s uncover the iteration process of nested for loops.

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 ".

Example of Nested for Loops

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“.

Nested for Loops with range() Function

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).

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

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.

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:

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✌✌