i know that my will seem trivial,but i cant figure out why isn't 'stop' equal to zero, since 'start' value is already overwritten.But when i simulate the same scenario out of the function it does indeed overwrite it.Am i missing something here?
def interval(start, stop =None, step = 1 ):
'Imitates range() for step >0 '
if stop is None:
start, stop = 0, start #since start is already 0, why isn't stop as well?
print start,stop , step
result = []
i = start
while i< stop:
result.append(i)
i+=step
return result
This expression
start, stop = 0, start
will NOT be evaluated like this
start = 0
stop = start
but will be evaluated by pushing both the values to the stack and the top two values will be rotated (so that the values will be swapped) and the values are assigned back to start
and stop
. Lets consider,
a = 1
a, b = 0, a
If we look at the disassembled code
import dis
dis.dis(compile("a = 1; a, b = 0, a", "<string>", "exec"))
it would look like
1 0 LOAD_CONST 0 (1)
3 STORE_NAME 0 (a)
6 LOAD_CONST 1 (0)
9 LOAD_NAME 0 (a)
12 ROT_TWO
13 STORE_NAME 0 (a)
16 STORE_NAME 1 (b)
19 LOAD_CONST 2 (None)
22 RETURN_VALUE
The LOAD_*
operations will load the content in to the stack. If you look at
6 LOAD_CONST 1 (0)
9 LOAD_NAME 0 (a)
the values, 0
and the value in a
are pushed to the stack and then ROT_TWO
, rotates the values in the top two positions of the stack. And finally
13 STORE_NAME 0 (a)
16 STORE_NAME 1 (b)
assigns the rotated values to a
and b
respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With