DEV Community

Discussion on: 12 Function tricks every Python developer should know

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited
  1. Pass by reference vs value

Python does neither. It has names which are bound to values. Values can be either mutable or immutable. This isn't really advanced, so much as unusual, but it is very important to understand when working in Python!

So, in...

answer = 42
insight = answer
insight = 4

...the name answer is bound to the value 42. insight is initially bound to the same value that answer is (names cannot be bound to other names). On the third line, insight is rebound to the value 4.

The behavior you're referring to is actually related to whether the data type being passed is mutable or immutable.

Immutable types seem to behave like pass-by-value because the value cannot be modified.

def increment(num):
    num = num + 1
    return num

spam = 5
eggs = increment(spam)
print(spam)  # 5
print(eggs)  # 6

In that example, foo is passed to increment(), so the parameter num gets bound to the same value as foo. This is identical to num = foo, by the way. However, an integer is immutable, meaning that value cannot be modified. So, num = num + 1 actually rebinds to a new value, 6, which is returned and bound to eggs.

Mutable data types, on the other hand, seem to behave like "pass-by-reference"...

def append_sum(numbers):
    numbers.append(sum(numbers))
    return numbers

spam = [1, 2]
eggs = append_sum(spam)

print(spam)  # [1, 2, 3]
print(eggs)  # [1, 2, 3]

Lists are mutable. Again, when we pass spam to the function, it's the same as if we said numbers = spam; numbers is now bound to the same value as spam. However, because that value is mutable, it can be changed directly, which we do with our numbers.append() call. Because both spam and numbers are still bound to the exact same value in memory, both see the mutation.

Then, when we return numbers, we wind up binding that same value to eggs as well. Thus, spam and eggs are (again) bound to the exact same value in memory.

Common immutable data types:

  • bool: True, False
  • str (string): "Hello, world!"
  • int, float, complex
  • tuple: (1, 2, 3)
  • bytes
  • frozenset

Common mutable data types:

  • list: [1, 2, 3]
  • set: {1, 2, 3}
  • dict (dictionary): {1: 'a', 2: 'b', 3: 'c'}
  • (Most objects)

Also watch Ned Batchelder's excellent talk on this topic.

Collapse
 
jsdude005 profile image
JS Dude

WOW. Well explained. Thanks, Jason