1

I stumbled upon a theoretical question about how python works, and it got me puzzled. I tried to understand exactly what happened but couldn't find the answer in google - I'm a beginner, so I don't even know the terminology to make the apropriate search.

On the following code, when calling the function it changes myList, while I only wanted to create a list2 which was a copy of list1 (myList).

myList = [1,2,3,4,5,(1,2),(3,4)]

def onlyTuples(list1):
    list2 = list1 # here is my question
    for index,e in enumerate(list2):
        if type(list2[index]) is not tuple:
            list2[index] = (list2[index],)
    return(list2)

print(myList)
create_new_list = onlyTuples(myList) # triggered by this call
print(myList)

It's all good if I change list2 = list1 to list2 = list(list1) and myList won't be changed when calling the function, but why?

The same thing doesn't happen with something like this:

a = 6
b = a
b = 7
print(a)

Any light upon the question will be appreciated. Thanks!

4
  • 1
    The line: ‘list2 = list1’ does not make a copy. Commented Jun 25, 2020 at 19:02
  • 1
    list2 = list(list1) creating a new list and list2 = list1 just assigning the list1 reference to list2 Commented Jun 25, 2020 at 19:03
  • 4
    See nedbatchelder.com/text/names.html Commented Jun 25, 2020 at 19:06
  • Yes, x = y never makes a copy. You should read that Ned Batchelder link, it should be illuminating. Commented Jun 25, 2020 at 20:29

2 Answers 2

3

In python lists are passed by reference, so when you pass list to a function you pass its address in the memory. list2 = list1 won't create a copy of the list, it will save in list2 the address saved in list1. so change of list2 will change list1, but the function in the class list doesn't save the address, it copy a sequence to a list

Sign up to request clarification or add additional context in comments.

3 Comments

oh I see, but why would I ever use that instead of directly changing list1? thanks man
there is not really a reason to make clones of list that way but in general pass by reference to function is used to change the list in the function without cloning the list and return a new one
Nothing is ever passed by reference in Python. The type of the object is irrelevant to the evaluation strategy, which is neither call by reference nor call by value
0

To make a copy of a list, use:

newList = myList.copy()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.