When you call modif
on liste1
and liste2
, it creates the variables tab1
and tab2
in the scope of the function call. You can think of tab1
as a reference to the list liste1
that exists in the caller's scope. You can verify that this is true by changing modif
to modify the list directly using one of its own member functions such as append
. For example:
def modif(tab1):
tab1.append('a')
liste1 = [1, 2, 3]
modif(liste1)
print(liste1)
prints out [1, 2, 3, 'a']
as expected.
However, when you say tab1 = tab2,
you are redefining tab1.
Remember, tab1
was a label that modif
used to reference liste1
, and tab2
was (and still is) a label that modif
used to reference liste2
.
The statement tab1 = tab2
tells python that tab1
is no longer a label for liste1,
but that it shall now be a label for tab2
(which is secretly a label for liste2
. You can see that this is true by running the following:
def modif(tab1, tab2):
tab1 = tab2
tab1.append('a')
liste1 = [1, 2, 3]
liste2 = [4, 5, 6, 7, 8]
modif(liste1, liste2)
print(liste2)
It prints out [4, 5, 6, 7, 8, 'a']
, verifying that tab1
is now a reference to liste2.
If you want liste1
to be changed in the function modif,
you need to modify tab1
directly, rather than setting tab1
to a new value, effectively destroying its link to liste1
. For example:
def modif(tab1, tab2):
for _ in range(len(tab1)): del tab1[0]
for ii in tab2: tab1.append(ii)
liste1 = [1, 2, 3]
liste2 = [4, 5, 6, 7, 8]
print(liste1[0], end=";")
modif(liste1, liste2)
print(liste1[0])
successfully prints 1;4
. This works because we are directly modifying tab1
rather than redefining it.