What is the difference between using list or not in python?

0

What is the difference in these 2 implementations

a=[1,2,3,4,5]
a=list([1,2,3,4,5])
    
asked by Kevin AB 17.07.2016 в 06:47
source

1 answer

4

list() is a constructor , a function that creates new objects with arguments what you provide When you create a list in this way a = [1, 2, 3] Python implicitly uses the constructor to create the list ( a = [1, 2, 3] is exactly the same as a = list([1, 2, 3]) ).

The important difference between the two ways of handling lists is that when you use list() you have as guarantee that the result is a new object, without any other reference pointing towards it. Consider this example:

>>> a = [1, 2, 3]
>>> b = a
>>> b[1] = 9
>>> a
[1, 9, 3]
>>> b
[1, 9, 3]

Without using list() , copying the contents of a to b simply copies the reference that points to the list in memory, not the list itself. So when you modify the content of b you also modify it in a and vice versa.

On the other side:

>>> a = [1, 2, 3]
>>> b = list(a)
>>> b[1] = 9
>>> a
[1, 2, 3]
>>> b
[1, 9, 3]

Using list() you create a new copy of a and save it in b . As a and b are already two different lists, when you modify one the other does not change.

    
answered by 17.07.2016 / 15:25
source