How can I create a nested loop in Python?


In the context of this code challenge, how can we create a nested loop in Python?


In Python, and almost every other programming language, you can create a nested loop by placing a loop within the block of another loop.

When nesting loops, keep in mind that on each iteration of the outer loop, the inner loop will completely run.


for first in first_names:
  # On each iteration of this outer loop
  # the inner loop will run to completion

  for last in last_names:
    print(first + " " + last)

#Write your function here
def exponents(bases, powers):
new_lst =
for base in bases:
for power in powers:
new_lst.append(base ** power)
return new_lst

Why does that code return something entirely different than the same thing, except an extra space at the start of the last line?

1 Like

And how can i create a bases row list with powers columns in order to separate results and present it in a matrix ?

crypto… – Please do not post flat (unindented) code. It is not Python, is hard to read, and requires guesswork as to your indentations. Use the </> icon.
Is this what you meant?

def exponents(bases, powers):
    new_lst = []
    for base in bases:
        for power in powers:
            new_lst.append(base ** power)
    return new_lst

Say that your bases are [2,3,4] and your powers[2,3]
Then if your powers function works properly, the output is a list of lists, like this:
[[4, 8], [9, 27], [16, 64]]

So for a simple matrix:

def mtrx(lst):
    for row in lst:        
        for col in row:
            print(col, end = "  "  )

Outputs this:

4  8  
9  27  
16  64  

If you want headers, it takes some formatting:

def print_table(lst, headers):
    bases = headers[2]
    powers = headers[3]    
    brackets = "{:4}   " * len(powers)    
    print("        {}".format(headers[0]))
    print(("{}    "+ brackets).format(headers[1], *(power for power in powers)))
    print("*" * len(powers) * 10)
    for idx, row in enumerate(table):        
        print(("  {}       "+ brackets).format(bases[idx], *(col for col in row)))

bases = [2,3,4]
powers = [2,3]
table = [[4, 8], [9, 27], [16, 64]]
headers = ("Powers", "Bases", bases, powers)

print_table(table, headers)

… which outputs:

Bases       2      3   
  2          4      8   
  3          9     27   
  4         16     64   

can you please explain why the [return new_lst] at the bottom must be at that indentation? What happens if it is directly under the penultimate line?

Thank you

Hi there, the return function needs to be indented two spaces as it is part of the function “exponents”. Everything that you want to be part of a function has to be indented at least to the first line.

I’m stuck on this one. Here’s my code.

def exponents(bases, powers):
  new_list = []
  for base in bases:
    for power in powers:
  return new_list

I get almost exactly the right answer except I get the last base raised to the lat power twice, ie

[2, 4, 8, 3, 9, 27, 4, 16, 64, 64]

Anyone know what I’m doing wrong?

Take a look at what is happening after you leave your for loops. :slight_smile:

1 Like

Believe it or not those two .append clauses were there on purpose because it wasn’t working at all previously…


1 Like