What's the difference between list1 = [] list2

2019-02-25 18:30发布

问题:

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 ?

回答1:

In the following case, you are creating one list and making 2 variables point to it; i.e. 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, ints (nor floats nor strs 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 (i.e 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.



回答2:

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