DEV Community

Discussion on: What is the most confusing thing to you in Python?

Collapse
 
math2001 profile image
Mathieu PATUREL

It's the case for every single thing in python except for int, float and str. These last three ones are passed by value (meaning we copy their value), everything else is passed by reference (meaning, as you said, the pass the "reference to the memory", the value isn't duplicated).

Have a look at this:

>>> mylist = [1, 2]
>>> ref = mylist
>>> ref.append(3)
>>> mylist
[1, 2, 3]
>>> mydict = {'key': 'value'}
>>> ref = mydict
>>> ref['key2'] = 'value2'
>>> mydict
{'key2': 'value2', 'key': 'value'}
>>> class MyCustomObject:
...     def __init__(self, name):
...             self.name = name
...
>>> myobject = MyCustomObject('Mathieu')
>>> ref = myobject
>>> ref.name = 'math2001'
>>> myobject.name
'math2001'
>>>

Quick tip:

If you don't want a list to be passed by reference, you can do that by calling .copy().

>>> mylist = [1, 2]
>>> copy = mylist.copy()
>>> copy.append(3)
>>> copy
[1, 2, 3]
>>> mylist
[1, 2]

The same works with dict. And obviously, for your custom object, you have to implement it yourself.

Gotcha

This copy methods on list and dict are only shallow copies. That means you don't duplicate the values too, they are passed my reference:

>>> mylist = [[1], 3]
>>> copy = mylist.copy()
>>> copy[0]
[1]
>>> copy[0].append(2)
>>> copy
[[1, 2], 3]
>>> mylist
[[1, 2], 3]
>>>

But if you want to do a deep copy:

>>> import copy
>>> mylist = [[1], 3]
>>> deepcopy = copy.deepcopy(mylist)
>>> deepcopy[0].append(2)
>>> deepcopy
[[1, 2], 3]
>>> mylist
[[1], 3]
>>>

Note: when you pass a variable by reference, it's a 2 way thing of course. If you edit the original on, it'll change the reference, and if you edit the reference, you change the original too.

Collapse
 
tmr232 profile image
Tamir Bahar

Basically, all types in Python are passed-by-reference. The distinction is between mutable and immutable types. I recommend reading Python's Data Mode. The first couple of paragraphs are really helpful.