Local variable definition in Python list comprehension

James Tsai jamestztsai at gmail.com
Thu Sep 1 16:18:53 EDT 2022


在 2022年9月1日星期四 UTC+2 16:15:17,<Ben Bacarisse> 写道:
> James Tsai <james... at gmail.com> writes: 
> 
> > I find it very useful if I am allowed to define new local variables in 
> > a list comprehension. For example, I wish to have something like 
> > [(x, y) for x in range(10) for y := x ** 2 if x + y < 80], or 
> > [(x, y) for x in range(10) with y := x ** 2 if x + y < 80]. 
> > 
> > For now this functionality can be achieved by writing 
> > [(x, y) for x in range(10) for y in [x ** 2] if x + y < 80].
> x and y are, to a first approximation, new local variables defined in a 
> list comprehension. I think you need to restate what it is you want.
> > Is it worthwhile to add a new feature like this in Python? If so, how 
> > can I propose this to PEP?
> To make any sort of case you'd need to give an example that does not 
> have a clearer way to write it already. Your working version is, to me, 
> clearer that the ones you want to be able to write. 
> 
> -- 
> Ben.

By local variable definition I mean binding a variable to a single value, so it doesn't include giving an iterable that a variable can take values iteratively, e.g. 'for x in range(10)'. Does it not worth introducing a specific syntax to do this, instead of creating a new list ad hoc to define the variable like 'for y in [1]'?


More information about the Python-list mailing list