简体   繁体   中英

What's the difference between list1 = [] list2 = [] and list1 = list2 = [] in python?

I just started using python and I am trying to initialize two lists using list comprehensions. Like this

list1 = list2 = [0.0] * 57

When i do this and insert these lists with values i am getting a different set of values (incorrect values) when compared to the values i get when i initialize these lists seperately. Like

list1 = [0.0] * 57
list2 = [0.0] * 57

What is happening in the first case ? Why am I getting different answers for these 2 cases ?

The first one sets list1 and list2 to both refer to the same list. The second one defines a new list for each name.

In the following case, you are creating one list and making 2 variables point to it; ie 2 references to the same object:

list1 = list2 = [123] * 3
list1.append(456)

print list1 =>  # prints [123, 123, 123, 456]
print list2 =>  # prints [123, 123, 123, 456]
print list1 is list2   # prints True

whereas this creates 2 new lists and assigns one to list1 and the other to list2 :

list1 = [123] * 3
list2 = [123] * 3
# or  list1, list2 = [123] * 3, [123] * 3

list1.append(456)

print list1  # prints [123, 123, 123, 456]
print list2  # prints [123, 123, 123]
print list1 is list 2  # prints False

This has to do with whether values are copied or stored in variables by reference. In the case of immutable objects such as integers and strings, this doesn't matter:

# a and b contain the same int object
# but it's OK because int's are immutable
a = b = 1
a += 2  # creates a new int from 1+2 and assigns it to `a`
print b  # => 1  ... b is unchanged
print a  # => 3

In other words, int s (nor float s nor str s etc) have no methods that change the value you're calling the method on; instead, they all return new instances of that type; so -5 returns a new int -5 not the existing int 5 modified; also, a += 2 is equivalent to a = a + 2 where a + 2 (ie the method __add__ called on a) returns a fresh int whose value is a + 2 and a reference to that gets assigned back to a .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM