Predict the output of these two expressions on Python console
Look at the bytecode Python generates for the expression s[a] += b. It becomes clear how that happens.
It works step by step
- Put the value of s[a] on Top Of Stack(TOS).
- Perform TOS += b. This succeeds, If TOS refers to a mutable object. That is why appending item to list is successful.
- Assign s[a] = TOS. This fails, If s is immutable. TypeError, because of tuple are immutable in above example.
Things to learn
- Putting mutable items in tuples is not a good idea.
- Augmented assignment is not an atomic operation — we just saw it throwing an exception after doing part of its job.
- Inspecting Python bytecode is not too difficult, and is often helpful to see what is going on under the hood.
- Look at the bytecode Python generates for the expression s[a] += b. It becomes clear how that happens.
- Python | Priority key assignment in dictionary
- Python - Maximum value assignment in Nested Dictionary
- Different Forms of Assignment Statements in Python
- Assignment Operators in Python
- Python - Sequence Assignment to Words
- Important differences between Python 2.x and Python 3.x with examples
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- Python | Add Logging to a Python Script
- Python | Add Logging to Python Libraries
- Python | Visualizing O(n) using Python
- Python | Index of Non-Zero elements in Python list
- Python | Convert list to Python array
- MySQL-Connector-Python module in Python
- Python - Read blob object in python using wand library
- Python | PRAW - Python Reddit API Wrapper
- twitter-text-python (ttp) module - Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : nidhi_biet