Local variable definition in Python list comprehension

Cameron Simpson cs at cskk.id.au
Thu Sep 1 18:11:06 EDT 2022


On 02Sep2022 07:01, Chris Angelico <rosuav at gmail.com> wrote:
>On Fri, 2 Sept 2022 at 06:55, James Tsai <jamestztsai at gmail.com> wrote:
>> No but very often when I have written a neat list/dict/set 
>> comprehension, I find it very necessary
>> to define local variable(s) to make it more clear and concise. Otherwise I have to break it down
>> to several incrementally indented lines of for loops, if statements, and variable assignments,
>> which I think look less nice.
>
>Well, if it's outgrown a list comp, write it on multiple lines. Like I
>said, not everything has to be a one-liner.

True, but a comprehension can be more expressive than a less 
"functional" expression (series of statements).

James, can you provide (a) a real world example where you needed to 
write a series of statements or loops and (b) a corresponding example of 
how you would have preferred to have written that code, possibly 
inventing some syntax or misusing ":=" as if it workeed they way you'd 
like it to work?

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list