In python you can change a list like this:
In [303]: x = [1,2,3,4,5,6]
In [304]: x[x <= 3]+=3
In [305]: x
Out[306]: [4, 2, 3, 4, 5, 6]
I have known about this for some time now, but I don’t think I fully understand whats going on behind the scenes. I would appriciate, if someone would find the time to explain.
In [307]: x = [1,2,3,4,5,6]
In [308]: dis.dis('x[x <= 3]+=3')
0 SETUP_LOOP 30811 (to 30814)
3 SLICE+2
4 STORE_SUBSCR
5 DELETE_SUBSCR
6 SLICE+2
7 DELETE_SLICE+1
8 FOR_ITER 15659 (to 15670)
11 DELETE_SLICE+1
In [309]: x
Out[309]: [1, 2, 3, 4, 5, 6]
In [310]: x[x <= 3]+=3
In [311]: x
Out[311]: [4, 2, 3, 4, 5, 6]
In [312]: x<=3
Out[312]: False
In [313]: x[False]+=3
In [314]: x
Out[314]: [7, 2, 3, 4, 5, 6]
x <= 3is a boolean expression. Since in Python, thebooleantype is a subclass ofint, theFalseoutcome is interpreted as0, so the end effect is:Or, demonstrated in a different way:
The
dis.dis()method doesn’t work with strings; it works with code objects (or something that contains code, such as a function, method, class, or module), or with bytecode. The fact that it seems to be able to decode your string is a happy coincidence;SETUP_LOOPis opcode 120 (the ASCII value forx), the whole string is being interpreted as a set of opcodes and offsets.Use a function instead: