One thing to know about lists is that they contain references (pointers) to list objects rather than the list itself. This can be seen by running the following code:
>>> list1 = [0, 1, 2, 3]
>>> list2 = list1
>>> list1[0] = 5
>>> list2
[5, 1, 2, 3]
Here, list1
stores a reference to the list [0, 1, 2, 3]
, and list2
is given that same reference. When the list is modified through the reference in list1
, the list referenced by list2
is also modified.
>>> def foo(bar):
for i in range(2):
if bar == []:
bar.append(4)
else:
bar[0] += 1
>>> myvar = []
>>> foo(myvar)
>>> myvar
[5]
Passing the list myvar
to the function foo()
as the argument bar
assigns a pointer to the list []
to the parameter bar
. Since myvar
and bar
reference the same list, when the list is modified through bar
, retrieving the list through myvar
reflects the same change.
Hopefully this clarifies any confusion!