Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does variable assignment work like this in lists?

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?

like image 398
Rob Avatar asked Aug 26 '26 06:08

Rob


2 Answers

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.

like image 194
Raymond Hettinger Avatar answered Aug 28 '26 19:08

Raymond Hettinger


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.

like image 35
Justin Niessner Avatar answered Aug 28 '26 18:08

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!