detaching comprehensions
bob gailer
bgailer at gmail.com
Fri Sep 8 17:06:25 EDT 2017
I don't know whether you wanted a reply, since you did not ask for one.
I am not even sure what your point is. See other comments below.
On 9/8/2017 4:24 PM, Stefan Ram wrote:
> Maybe you all know this, but to me this is something new.
> I learnt it by trial and error in the Python 3.6.0 console.
>
> Most will know list comprehensions:
>
> |>>> [ i for i in range( 3, 5 )]
> |[3, 4]
>
> I found out that the comprehension can be detached from the list:
>
> |>>> k =( i for i in range( 3, 5 ))
>
> but one must use an extra pair of parentheses around it in the
> assignment.
>
> Now I can insert the "generator" »k« into a function call,
> but a spread operator should cannot be used there.
>
> |>>> sum( k )
> |7
>
> »sum« expects exactly two arguments, and this is what »k«
> provides.
Where did you get that idea. If you look at the docs you will see:
"sum(iterable[, start])
Sums start and the items of an iterable from left to right and returns
the total. start defaults to 0."
sum expects 1 or 2 arguments; when you write sum(k) you are providing 1
argument.
>
> But to insert it again into the place where it was "taken
> from", a spread operator is required!
>
> |>>> k =( i for i in range( 3, 5 ))
> |>>> [ *k ]
> |[3, 4]
"taken from"??
k is a generator object.
Clear?
Bob Gailer
More information about the Python-list
mailing list