[Python-Dev] (no subject)

Donald Stufft donald at stufft.io
Tue Feb 10 07:31:30 CET 2015


> On Feb 10, 2015, at 12:55 AM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> 
> Donald Stufft wrote:
>> However [*item for item in ranges] is mapped more to something like this:
>> result = []
>> for item in iterable:
>>    result.extend(*item)
> 
> Actually it would be
> 
>   result.extend(item)
> 
> But if that bothers you, you could consider the expansion
> to be
> 
> result = []
> for item in iterable:
>   for item1 in item:
>      result.append(item)
> 
> In other words, the * is shorthand for an extra level
> of looping.
> 
>> and it acts differently than if you just did *item outside of a list comprehension.
> 
> Not sure what you mean by that. It seems closely
> analogous to the use of * in a function call to
> me.
> 

Putting aside the proposed syntax the current two statements are currently
true:

1. The statement *item is roughly the same thing as (item[0], item[1], item[n])
2. The statement [something for thing in iterable] is roughly the same as:
   result = []
   for thing in iterable:
       result.append(something)
   This is a single loop where an expression is ran for each iteration of the
   loop, and the return result of that expression is appended to the result.

If you combine these two things, the "something" in #2 becuase *item, and since
*item is roughly the same thing as (item[0], item[1], item[n]) what you end
up with is something that *should* behave like:

result = []
for thing in iterable:
    result.append((thing[0], thing[1], thing[n]))


Or to put it another way:

>>> [*item for item in [[1, 2, 3], [4, 5, 6]]
[(1, 2, 3), (4, 5, 6)]


Is a lot more consistent with what *thing and list comprehensions already mean
in Python than for the answer to be [1, 2, 3, 4, 5, 6].
---
Donald Stufft
PGP: 7C6B 7C5D 5E2B 6356 A926 F04F 6E3C BCE9 3372 DCFA



More information about the Python-Dev mailing list