a = [0]
b = a
a[0] = 1
print b
this will print 1, why does this work for lists but not for int's or float's or anything like that?
a = [0] # create an int, create a container referencing the int, let "a" reference the container
b = a # let "b" reference the same container as "a"
a[0] = 1 # create another int, let container "a" reference the new int
print b # "b" and "a" refer to the same container with the new contents
See this Python Tutor visualization for a clearer picture of what is happening.
All types in Python are reference types. The trick is that some are mutable and some are not. ints and floats are immutable. The value 42 can't be changed. Every time you assign a new value to a variable, it's pointing to a new value.
a and b both refer to the same array in your code. That's why, when you modify the array using one identifier, you see that change reflected when accessing the value using the other identifier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With