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

前端 未结 2 906
一向
一向 2021-01-22 17:01

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

相关标签:
2条回答
  • 2021-01-22 17:18

    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.

    0 讨论(0)
  • 2021-01-22 17:18

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

    0 讨论(0)
提交回复
热议问题