Answer the question
In order to leave comments, you need to log in
Why does changing a variable in a list not affect a variable outside that list?
In general, recently I was wooling the random library and watching how it works. All sorts of randrange, randint and the like.
And I decided to see if it is possible to change the value in the array using this construction:
from random import randrange
a, b, c = 4, 6, 8
r = [a, b, c]
r[randrange(0, 3)] = 1
print(r)
print(a, b, c)
[4, 1, 8] # Ну или другое число
4, 6, 8
Answer the question
In order to leave comments, you need to log in
You need to understand that "=" is 'assign', and besides that, you need to know the difference between mutable vs immutable. Usually textbooks describe this in detail.
Your code has written a reference to the number 1 in the second element of the list instead of the reference to the number 6 that was there before, and the variable b still stores a reference to 6. It is not clear what surprises you.
from random import randrange
a, b, c = 4, 6, 8
r = ['a', 'b', 'c']
exec("{} = 1".format(r[randrange(0, 3)]))
print(a, b, c, r)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question