An exercise to help build the right mental model for Python data. The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening:
An exercise to help build the right mental model for Python data. The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening:
It’s always fun to guess whether python will call
__add__or__iadd__.__add__is called with+and__iadd__is called with+=, and there is a difference: https://www.reddit.com/r/PythonLearning/comments/1nw08wu/right_mental_model_for_python_data/Except if
__iadd__doesn’t exist on the type, then__add__is called. The variable is always reassigned. Quick example:x = (0, [1, 2]) try: x[1] += [3] # calls list.__iadd__, then reassigns x[1] except TypeError as e: print(e) x += (4,) # calls tuple.__add__, then reassigns x print(x)What is printed?
Thanks. I didn’t know: https://memory-graph.com/#code=x+%3D+(0%2C+[1%2C+2]) try%3A ++++x[1]+%2B%3D+[3]++%23+calls+list.__iadd__%2C+then+reassigns+x[1] except+TypeError+as+e%3A ++++print(e) x+%2B%3D+(4%2C)++%23+calls+tuple.__add__%2C+then+reassigns+x print(x) class+MyClass%3A ++++ ++++def+__add__(self%2C+other)%3A ++++++++print(‘__add__’) ++++++++ ++++%23def+__iadd__(self%2C+other)%3A ++++%23++++print(‘__iadd__’) a+%3D+MyClass() b+%3D+MyClass() a+%2B%3D+b++%23+calls+__add__+if+__iadd_+doesn’t+exist &play=