list()is a constructor , a function that creates new objects with the arguments 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]it's exactly the same as a = list([1, 2, 3])).
The important difference between the two ways of handling lists is that when using list()you are guaranteed that the result is a new object, without any other references pointing to 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 aa bsimply copies the reference that points to the list into memory, not the list itself. So when you modify the content of byou also modify it in aand vice versa.
On the other hand:
>>> a = [1, 2, 3]
>>> b = list(a)
>>> b[1] = 9
>>> a
[1, 2, 3]
>>> b
[1, 9, 3]
Using list()tu create a new copy of aand save it to b. Since aand bare already two different lists, when you modify one the other does not change.
list()
is a constructor , a function that creates new objects with the arguments you provide. When you create a list in this waya = [1, 2, 3]
Python implicitly uses the constructor to create the list (a = [1, 2, 3]
it's exactly the same asa = list([1, 2, 3])
).The important difference between the two ways of handling lists is that when using
list()
you are guaranteed that the result is a new object, without any other references pointing to it. Consider this example:Without using
list()
, copying the contents ofa
ab
simply copies the reference that points to the list into memory, not the list itself. So when you modify the content ofb
you also modify it ina
and vice versa.On the other hand:
Using
list()
tu create a new copy ofa
and save it tob
. Sincea
andb
are already two different lists, when you modify one the other does not change.