Python progression path – quiz

Python progression path – From apprentice to guru is a popular StackOverflow post. To categorize whether a person should take his beginner/intermediate course, one of the commentors posted this question:

python progression quick

I can better answer this question after reading Fluent Python. Example 1 and Example 2 deal with immutable and mutable data types – respectively. Let’s address each example individually.

Example 1

The id built in method returns the object’s memory address. We’ll use this to inspect the memory address for x and ythroughout the examples.

x and y point to the same memory address when they are first assigned.

>>> x = 42
>>> y = x
>>> id(x)
4298172632
>>> id(y)
4298172632

Because the value of x is immutable (e.g INT) and cannot be modified, by definition, a new memory address is allocated when x is modified. But, y‘s memory remains unmodified:

>>> x = x + 1
>>> id(x)
4298172608
>>> id(y)
4298172632
>>>

Example 2

Like Example 1, the memory address starts off the same:

>>> x = [1,2,3]
>>> y = x
>>> id(x)
4299948256
>>> id(y)
4299948256

Now that we are dealing with mutable data types, x can be modified in place and the memory address does not change:

>>> id(x)
4299948256
>>> id(y)
4299948256

Mutable default arguments

This quiz seems trivial but it isn’t. Understanding this will prevent a novice mistake of using mutable default arguments.

>>> def update(x, y=[]):
...     y.append(x)
...     return y
...
>>> list1 = ['a', 'b', 'c']
>>> list2 = [1, 2, 3]
>>> update('d', list1)
['a', 'b', 'c', 'd']
>>> update(4, list2)
[1, 2, 3, 4]
>>> list1
['a', 'b', 'c', 'd']
>>> list2
[1, 2, 3, 4]
>>> update('a')
['a']
>>> list3 = update('b')
>>> list3
['a', 'b']
>>> list4 = update('hello')
>>> list4
['a', 'b', 'hello']