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?

2
  • Have a read of this: stackoverflow.com/questions/3611760/scoping-in-python-for-loops Commented Oct 1, 2020 at 2: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? Commented Oct 1, 2020 at 2:29

1 Answer 1

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.

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

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.