Home > Mobile >  Python - does a variable inside the for loop get created only once or once per iteration?
Python - does a variable inside the for loop get created only once or once per iteration?

Time:12-15

In the following for loop, how many times is x created (i.e. how many times is a new piece of memory allocated) - only once or once per iteration? I'm assuming it's the former, but I'd like to be sure.

for _ in range(10):
    x = 3

CodePudding user response:

Disassembling the generated byte code is instructive:

Python 3.8.2 (default, May 18 2021, 11:47:11) 
[Clang 12.0.5 (clang-1205.0.22.9)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dis
>>> dis.dis('''for _ in range(10):
...   x = 3''')
  1           0 LOAD_NAME                0 (range)
              2 LOAD_CONST               0 (10)
              4 CALL_FUNCTION            1
              6 GET_ITER
        >>    8 FOR_ITER                 8 (to 18)
             10 STORE_NAME               1 (_)

  2          12 LOAD_CONST               1 (3)
             14 STORE_NAME               2 (x)
             16 JUMP_ABSOLUTE            8
        >>   18 LOAD_CONST               2 (None)
             20 RETURN_VALUE

Perhaps notice that LOAD_CONST does not as such create a new memory allocation; but the STORE_NAME for x is indeed inside the loop.

  • Related