0

I encountered an error in my Python 3 code, and after intense debugging, I found out that Python doesn't appear to assign lists correctly:

$ python3
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  5 2014, 20:42:22) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> test_1 = [12, 34]
>>> test_1
[12, 34]
>>> test_2 = [12, 34]
>>> test_2
[12, 34]
>>> test_2 = test_1
>>> test_2
[12, 34]
>>> test_1[0] = 'This changes in both arrays!'
>>> test_1
['This changes in both arrays!', 34]
>>> test_2
['This changes in both arrays!', 34]
>>> 

Why is this happening? Is this intended? How do I stop it from happening???

2 Answers 2

1

When you do test_2 = test_1 you are making test_2 point to the list pointed by test_1.

You could do instead:

>>> test_2 = test_1.copy()
Sign up to request clarification or add additional context in comments.

1 Comment

or test_2 = test_1[:]
1

This is expected behavior. Python lists pass by reference. This means that when you assign a list, instead of making a copy of the list and assigning this new list to the new variable, it has both variables point at the same underlying list. This can be useful in a lot of cases. But it seems like you want to actually copy the list. To do so, do the following:

test_2 = list(test_1)

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.