2

Out of curiosity, I tried implementing a nested for loop using the same iterating variable in both the outer and inner for loops.

for i in range(3):
    for i in range(4):
        print("i = %s" % i)

What exactly is going on behind the scene here? BTW, the inner print is executed 12 times.

9
  • The for statement does not use i for looping. It just assigns current iteration value to i before running loop body. That's why it runs fine. The print will only show inner for's i values though. Commented Aug 17, 2017 at 10:58
  • The inner loop rewrites the outer i variable. This is fine as long as you aren't doing anything with it. Commented Aug 17, 2017 at 10:59
  • 2
    @vaultah Couldn't find a duplicate? Commented Aug 17, 2017 at 11:00
  • @cᴏʟᴅsᴘᴇᴇᴅ nope, I didn't search :) Commented Aug 17, 2017 at 11:02
  • @omu_negru Um, that's not a Python question, so that logic doesn't quite apply here. ;) Commented Aug 17, 2017 at 11:03

2 Answers 2

1

The variable "i" is iterating the elements in the outer loop, but then is re-set to iterate the elements in the inner loop. And so on. The bottom line is that you're gonna print the elements of the inner loop 3 times (the size of the outer one)

Sign up to request clarification or add additional context in comments.

Comments

1

What happens is that the second i shadows the first one, so the print instruction will only reffer to the inner loop i

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.