[Python-ideas] Temporary variables in comprehensions

Neil Girdhar mistersheik at gmail.com
Wed Feb 21 06:37:11 EST 2018


You should give an actual motivating example.  I think none of these 
suggestions are more readable than just writing things out as a for loop.  
You argue that you want to avoid appending to a result list.  In that case, 
I suggest writing your pattern as a generator function.

Best,

Neil

On Thursday, February 15, 2018 at 2:03:31 AM UTC-5, fhsxfhsx wrote:
>
> As far as I can see, a comprehension like 
> alist = [f(x) for x in range(10)]
> is better than a for-loop
> for x in range(10):
>   alist.append(f(x))
> because the previous one shows every element of the list explicitly so 
> that we don't need to handle `append` mentally.
>
> But when it comes to something like
> [f(x) + g(f(x)) for x in range(10)]
> you find you have to sacrifice some readableness if you don't want two 
> f(x) which might slow down your code.
>
> Someone may argue that one can write
> [y + g(y) for y in [f(x) for x in range(10)]]
> but it's not as clear as to show what `y` is in a subsequent clause, not 
> to say there'll be another temporary list built in the process.
> We can even replace every comprehension with map and filter, but that 
> would face the same problems.
>
> In a word, what I'm arguing is that we need a way to assign temporary 
> variables in a comprehension.
> In my opinion, code like
> [y + g(y) for x in range(10) **some syntax for `y=f(x)` here**]
> is more natural than any solution we now have.
> And that's why I pro the new syntax, it's clear, explicit and readable, 
> and is nothing beyond the functionality of the present comprehensions so 
> it's not complicated.
>
> And I hope the discussion could focus more on whether we should allow 
> assigning temporary variables in comprehensions rather than how to solve 
> the specific example I mentioned above.
>
>
>  
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180221/75179455/attachment.html>


More information about the Python-ideas mailing list