Python assigning multiple variables to same value? list behavior -
i tried use multiple assignment show below initialize variables, got confused behavior, expect reassign values list separately, mean b[0] , c[0] equal 0 before.
a=b=c=[0,3,5] a[0]=1 print(a) print(b) print(c) result is: [1, 3, 5] [1, 3, 5] [1, 3, 5]
is correct? should use multiple assignment? different this?
d=e=f=3 e=4 print('f:',f) print('e:',e) result: ('f:', 3) ('e:', 4)
if you're coming python language in c/java/etc. family, may stop thinking a "variable", , start thinking of "name".
a, b, , c aren't different variables equal values; they're different names same identical value. variables have types, identities, addresses, , kinds of stuff that.
names don't have of that. values do, of course, , can have lots of names same value.
if give notorious b.i.g. hot dog,* biggie smalls , chris wallace have hot dog. if change first element of a 1, first elements of b , c 1.
if want know if 2 names naming same object, use is operator:
>>> a=b=c=[0,3,5] >>> b true you ask:
what different this?
d=e=f=3 e=4 print('f:',f) print('e:',e) here, you're rebinding name e value 4. doesn't affect names d , f in way.
in previous version, assigning a[0], not a. so, point of view of a[0], you're rebinding a[0], point of view of a, you're changing in-place.
you can use id function, gives unique number representing identity of object, see object when is can't help:
>>> a=b=c=[0,3,5] >>> id(a) 4473392520 >>> id(b) 4473392520 >>> id(a[0]) 4297261120 >>> id(b[0]) 4297261120 >>> a[0] = 1 >>> id(a) 4473392520 >>> id(b) 4473392520 >>> id(a[0]) 4297261216 >>> id(b[0]) 4297261216 notice a[0] has changed 4297261120 4297261216—it's name different value. , b[0] name same new value. that's because a , b still naming same object.
under covers, a[0]=1 calling method on list object. (it's equivalent a.__setitem__(0, 1).) so, it's not really rebinding @ all. it's calling my_object.set_something(1). sure, object rebinding instance attribute in order implement method, that's not what's important; what's important you're not assigning anything, you're mutating object. , it's same a[0]=1.
user570826 asked:
what if have,
a = b = c = 10
that's same situation a = b = c = [1, 2, 3]: have 3 names same value.
but in case, value int, , ints immutable. in either case, can rebind a different value (e.g., a = "now i'm string!"), won't affect original value, b , c still names for. difference list, can change value [1, 2, 3] [1, 2, 3, 4] doing, e.g., a.append(4); since that's changing value b , c names for, b b [1, 2, 3, 4]. there's no way change value 10 else. 10 10 forever, claudia vampire 5 forever (at least until she's replaced kirsten dunst).
* warning: not give notorious b.i.g. hot dog. gangsta rap zombies should never fed after midnight.
Comments
Post a Comment