-3

I dont understand the output from this piece of code.

def modif(tab1, tab2):
    tab1 = tab2


liste1 = [1, 2, 3]
liste2 = [4, 5, 6, 7, 8]
print(liste1[0], end=";")
modif(liste1, liste2)
print(liste1[0])

I thougth, the output would be " 1;4 " but it actually is "1;1". Could someone explain why this is?

GoodWood
  • 3
  • 1
  • Does this answer your question? [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – InSync Apr 22 '23 at 18:25
  • You can [visualize what happens](https://pythontutor.com/visualize.html#code=def%20modif%28tab1,%20tab2%29%3A%0A%20%20%20%20tab1%20%3D%20tab2%0A%0Aliste1%20%3D%20%5B1,%202,%203%5D%0Aliste2%20%3D%20%5B4,%205,%206,%207,%208%5D%0A%0Amodif%28liste1,%20liste2%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false). And read [names and values](https://people.cs.kuleuven.be/~danny.deschreye/Names_and_Values.html). – jarmod Apr 22 '23 at 18:37

1 Answers1

0

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.

jamman2000
  • 50
  • 6