A += B Assignment Riddle in Python

Predict the output of these two expressions on Python console

  • On console

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    Geek = (1, 2, [8, 9])
    Geek[2] += [3, 4]

    chevron_right

    
    

    Output:

    Explanation:



    • 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 successfull.
      • 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.


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.