R
R
Rild22022-03-17 12:38:30
Python
Rild2, 2022-03-17 12:38:30

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

In theory, everything should be very simple: one variable from the list [a, b, c] will become one.
However! This code:
print(r)
print(a, b, c)

Outputs:
[4, 1, 8]  # Ну или другое число
4, 6, 8

Why is this happening? In the array, what, are their local variables created or what?
And more, how it is possible to address to this changed variable? And without using indexes.
r[r.index(a)] doesn't work, I checked.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dr. Bacon, 2022-03-17
@Rild2

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.

S
Sergey Gornostaev, 2022-03-17
@sergey-gornostaev

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.

I
Ivan Chetchasov, 2022-03-17
@TalismanChet

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)

and everything should work

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question