Sunday, December 14, 2025
HomeLanguagesA += B Assignment Riddle in Python

A += B Assignment Riddle in Python

Predict the output of these two expressions on Python console

  • On console




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

    
    

    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 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.
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32448 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6817 POSTS0 COMMENTS
Nicole Veronica
11954 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12031 POSTS0 COMMENTS
Shaida Kate Naidoo
6953 POSTS0 COMMENTS
Ted Musemwa
7202 POSTS0 COMMENTS
Thapelo Manthata
6899 POSTS0 COMMENTS
Umr Jansen
6883 POSTS0 COMMENTS