[Python-ideas] Fwd: Fwd: Fwd: unpacking generalisations for list comprehension
Daniel Moisset
dmoisset at machinalis.com
Tue Oct 18 04:01:23 EDT 2016
On 17 October 2016 at 21:22, Random832 <random832 at fastmail.com> wrote:
>
> No, it's not.
>
> For a more concrete example:
>
> [*range(x) for x in range(4)]
> [*(),*(0,),*(0,1),*(0,1,2)]
> [0, 0, 1, 0, 1, 2]
>
> There is simply no way to get there by using flatten(range(4)).
the equivalent flatten for that is:
flatten(range(x) for x in range(4)) ; flatten has no magic so will not
replace a piece of code with two range calls (like your example) for code
with one.
I see some mention that flatten does not cover all cases; but correct me if
I'm wrong with this statement:
Any case of [*<exp1> for <vars> in <exp2>] could be replaced with
flatten(<exp1> for <vars> in <exp2>). Where flatten is defined as
def flatten(it):
return [x for for subit in it for x in subit]
(there is a slight difference where I'm making flatten iterable instead of
a list)
What perhaps was confusing is that in the case where <exp1> and <vars> are
the same, you can also write flatten(<exp2>).
So, for me, this feature is something that could be covered with a (new)
function with no new syntax required. All you have to learn is that instead
of [*...] you use flatten(...)
Am I wrong? I keep reading people on both sides saying "flatten is not
enough in all cases", and I can find a counterexample (even for 1 level
flatten which is what I used here)
PS: or alternatively, flatten = lambda it: list(itertools.chain(it)) # :)
PPS: or if you prefer to work with iterators, flatten = itertools.chain
--
Daniel F. Moisset - UK Country Manager
www.machinalis.com
Skype: @dmoisset
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161018/17516529/attachment-0001.html>
More information about the Python-ideas
mailing list