lupus
lupus

Reputation: 65

Python Theory About Equal Operator and Array Definition

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!

Upvotes: 1

Views: 70

Answers (2)

lupus
lupus

Reputation: 65

To make a copy of a list, use:

newList = myList.copy()

Upvotes: 0

Shahar Daichman
Shahar Daichman

Reputation: 54

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

Upvotes: 3

Related Questions