![]() |
| Are list/dict comprehensions interpreted really sequentially? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Are list/dict comprehensions interpreted really sequentially? (/thread-37361.html) |
Are list/dict comprehensions interpreted really sequentially? - anata2047 - May-31-2022 In any programming course/books I learned the intro section mentions the sequential mode of execution of any program (implying at least the sequential way of navigating through lines in an editor). But I suppose this sequential mode is also valid for token-by-token processing. Yet, in Python list and dictionary comprehensions, like sum([i**2 for i in range(3)])or results = {n: n ** 2 for n in range(10)} the operational part of the for loop (i**2, n ** 2) comes before the definitive. And it is not sequential. How does this happen in Python? RE: Are list/dict comprehensions interpreted really sequentially? - Gribouillis - May-31-2022 It is not clear what you mean by «interpreted really sequentially». In certain syntax constructs, Python executes code in a non left-to-right way. For example in a = x + y if x * y > 2 else x - 1the test x * y > 2 is executed first, then only one of x + y or x - 1 is executed.Similarly in comprehension constructs, the for loops iterations are actually set up before the body is executed, but the body appears syntactically before the for loop. RE: Are list/dict comprehensions interpreted really sequentially? - anata2047 - May-31-2022 (May-31-2022, 08:24 PM)Gribouillis Wrote: In certain syntax constructs, Python executes code in a non left-to-right way.How does this actually is implemented and what are these syntax constructs (apart from already mentioned)? To get to test x * y > 2, Python should first go through a = x + y.Why it won't throw "a variable not defined" error? RE: Are list/dict comprehensions interpreted really sequentially? - Gribouillis - May-31-2022 (May-31-2022, 08:37 PM)anata2047 Wrote: How does this actually is implementedPython converts the code to an intermediate language named «bytecode». By using the dis module, one can examine this bytecode. Here is how python compiles the above conditional expression. It is apparent in the bytecode that the test in the middle is executed first. Of course, if x and y are not defined, an error will result.>>> import dis >>> dis.dis("a = x + y if x * y > 2 else x - 1") 1 0 LOAD_NAME 0 (x) 2 LOAD_NAME 1 (y) 4 BINARY_MULTIPLY 6 LOAD_CONST 0 (2) 8 COMPARE_OP 4 (>) 10 POP_JUMP_IF_FALSE 20 12 LOAD_NAME 0 (x) 14 LOAD_NAME 1 (y) 16 BINARY_ADD 18 JUMP_FORWARD 6 (to 26) >> 20 LOAD_NAME 0 (x) 22 LOAD_CONST 1 (1) 24 BINARY_SUBTRACT >> 26 STORE_NAME 2 (a) 28 LOAD_CONST 2 (None) 30 RETURN_VALUE >>> For details about the syntax of Python and how it works, I strongly recommend reading The Python language reference. |