List comprehension - 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: List comprehension (/thread-19841.html) |
List comprehension - Uchikago - Jul-17-2019 Please explain why this doesn't work seq=[1,2,3] def a(): return x+2 x=[a() for x in seq]I thought a list comprehension create a new local scope for the expression itself, and when we use a(), x is searched by the LEGB rule and can find the x in the enclosing scope, am i correct ? RE: List comprehension - perfringo - Jul-17-2019 Following is friendly banter. No offence intended. These repeated questions reminded me 'sketch' from Three Men in a Boat by Jerome K Jerome. One can read whole episode here, but for immediate usage I provide prescription: Quote:1 lb. beefsteak, with As for question: it's always good practice to use functions with parameters. >>> seq = [1, 2, 3] >>> def a(x): return x + 2 >>> lst = [a(num) for num in seq] >>> lst [3, 4, 5] RE: List comprehension - ThomasL - Jul-17-2019 (Jul-17-2019, 02:46 AM)Uchikago Wrote: Please explain why this doesn't workSorry but this code is complete nonsense and that´s the reason it´s not working. You definitely should watch some tutorial, e.g. this one here. RE: List comprehension - scidam - Jul-18-2019 Not sure, is this question very simple, or very tricky...So, lets do some examples here. First of all, lets start with the following example: def a(): return x + 2 for x in range(10): print(a(), globals().get('x')) Everthing works as expected: for loop creates x-values in the global scope, and the variable x is visible from the a()-function.List comprehensions are functions too. To show this, lets consider the following bytecode, e.g. import dis dis.dis("[x for x in range(5, dont_execute_me='I am in op-code')]") Line #25 executes list comprehension-function; line #21 creates range; How to make it works... We just need to declare something like this: [a() for x in range(5); global x] ; but this isn't allowed by Python syntax.Nevertheless, we can do some injection, e.g. [(globals().update({"x":x}), a())[-1] for x in range(3)] Everything works fine! This is just for fun, don't do this in any valuable code.
|