0

I have this weird question about lists in python and how they actually work. As you see in the following code it is a pretty easy code. But what I expected to get as output is really different from what I really got

I expected to get:


l1 = [10,4,5]
l2 = [3,1,2,4,5]
l3 = [7,8]

But I got :

l1 = l2 = [10,1,2,4,5]
l3 = [7,8]
    def insert(lst1,lst2,p):
    if p>0:
        lst1[p:p] = lst2
    else:
        lst1 = lst2
    return lst1

l1 = [3,4,5]
l2 = insert(l1,[1,2],1)
l1[0] = 10
l3 = insert(l2,[7,8],0)
print(l1)
print(l2)
print(l3)

Can anyone please explain? thanks in advance

Noubah
  • 13
  • 4
  • The question here is vague and there seem to be multiple things you're wondering about; but there are many existing questions on Stack Overflow that generally cover the model properly. The important thing to understand is that this is **not** really about "how lists work"; it's about "how *names* work". The short version is that the first call will modify the passed-in `l1` and then return that same list, and then outside the function `l2` becomes another name for, still, the same list. – Karl Knechtel Oct 22 '22 at 00:12
  • The second call will start out using `lst1` as a name for that list, and `lst2` as a name for the new `[7, 8]` list. Then it will change so that `lst2` locally names the `[7, 8]` list instead, so that *that* list is what gets returned, and re-named as `l3` outside the function. The `=` operator in Python **does not copy**; functions both accept and return **values, not names**; and parameters are *local names for the passed-in values* (the arguments of the function call). – Karl Knechtel Oct 22 '22 at 00:14

0 Answers0