0

So like, i'd want

i,j = 3,3

for i in range(10):
   j = i

print(i,j)

to print me "3 9", but in reality it prints me "9 9". I'm coming from lua, and this is possible to do since a local variable "i" is automatically created for the cycle, so that there's an "i" that reaches 9 inside the loop, but there's still an "i" outside the loop that's still at 3.

Is this possible? Or do i must use a variable that has not previously been used?

  • Have a read of this: https://stackoverflow.com/questions/3611760/scoping-in-python-for-loops – Macattack Oct 01 '20 at 02:23
  • yea, that's exactly the answer i needed, thanks, even though it kind of sucks. i did search for the answer before posting it, but i wasn't aware of what scoping meant, mb. now... how do i close the post? – AnataBakka Oct 01 '20 at 02:29

1 Answers1

1

You are itself iterating with i where it is already declared before with j as 3 and in loop, values of both variables increase. So use a different variable. If you add a print(i,j) you will see both increase by 1 in each iteration, because i is the variable which is used to iterate over the range, so the old i value gets overwritten. Perhaps use a different variable like k to iterate instead of i. Or instead variables have scope, global and local, then use the global keyword. List comprehension could be considered.

Wasif
  • 14,755
  • 3
  • 14
  • 34