Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

kamal diriye
kamal diriye
1,597 Points

understanding the logic in nested for loops

Im going to do my best to explain myself.

This is the first time I've came across Nested For Loops, and I understand it to a second extent. For example:

   for column in self.columns:
            for num in range(1, self.size + 1):
                self.locations.append(f'{column}{num}')

I understand by this that each column will be looped through with all the possible values nn the numbers for loop, e.g A1 A2 A3 (if i am wrong please correct me)

  • The one thing I am finding it hard to understand is when these Nested For Loops should be used.
  • And also, what is the best way of understanding Nested For Loops when it has a lot of logic(code). If someone could please answer Thanks!

2 Answers

Hey kamal diriye, Nested For loops are good for when you have to loop through a specific amount of times within a block of code that is looping through a specific amount of times.

Here is an example so that we can go line by line and see what is happening:

colors = ["Red", "White", "Blue"]
nums = [1, 2, 3]

for color in colors:
    for num in nums:
        print(color, num)

The inner loop will run 3 times for each color in the outer loop.

  • The first step will be, for Red in ["Red", "White", "Blue"], for 1 in [1, 2, 3]... print Red 1.
  • Then it will be for 2 in [1, 2, 3], print Red 2.
  • Lastly, for 3 in [1, 2, 3], print Red 3

Once all the inner values have been run, the next value in the for loop will run all of the inner values for White, then Blue and so on.

Using nested for loops is great when you have an iterable that needs the same code repeated a set amount of times for each item in the iterable. There will be times that this is necessary to keep your code DRY and tidy.

Hopefully this example helps you understand the logic. But one of the best things you can do is to play around with the code. Print some cool designs using nested for loops. Try to understand what is happening by the console output.