Search code examples
for-loopnested-for-loop

When to use range function in python for loops


If we are able to create a for loop without using the range function, as in:

foods = [potato, pizza, spinach]

for food in foods:
  print(food)

why am I not able to do the same in this following nested for loops?

def exponents(bases, powers):
  results = []

  for i in range(len(bases)):
    for j in range(len(powers)):
      results.append(bases[i]**powers[j])
  return results

rather using this approach:

def exponents(bases, powers):
  results = []

  for i in bases:
    for j in powers:
      results.append(bases[i]**powers[j])
  return results

will result in an indexError:

IndexError: list index out of range

What is the difference between the single and nested for loops in regards to these variables?


Solution

  • When you use the range function, you are iterating the list index. When you use the list directly, you are iterating the objects in the list.

    Try this:

    def exponents(bases, powers):
      results = []
    
      for b in bases:
        for p in powers:
          results.append(b**p)
      return results  # not new