+ 2
Why does this output 5?
num1 = [1,3,4,5] num2 = num1 num2[0] = 5 print(num1[0]) I don't understand why this code outputs 5. Can someone walk me through this?
2 Answers
+ 7
Because arrays are passes by references so when you do num2 = num1 these two arrays are showinh to the same location in memory so when you change by one second is also changed
+ 3
Addition to Vukan's comment:
If you want to pass by value (copy it), you can use the deepcopy() method of the 'copy' module:
import copy
list1 = [1, 3, 4, 5]
list2 = copy.deepcopy(list1)
list2[0] = 5
print(list1[0]) # output: 1
As for a deeper explaination:
There are two types of passing data in Python, passing by value and passing by reference. Passing by value essentially makes a copy of the value of the thing, then gives that to the new thing. This keeps the new variable different from the original one. Passing by reference, on the other hand, is like pointing to something. The new variable points to the old one, and they are the same object, with different names. In fact, they are the same object at the system level; only one object truly exists, the two in the code are just names. When doing 'list1 = list2' you pass by reference, so any changes to list2 are done to list1, because they are really the same thing.