From: Ethan Furman on
Anthony Papillion wrote:
> Someone helped me with some code yesterday and I'm trying to
> understand it. The way they wrote it was
>
> subjects = (info[2] for info in items)
>
> Perhaps I'm not truly understanding what this does. Does this do
> anything different than if I wrote
>
> for info[2] in items
> subject = info[2]

Close -- the correct form is

for info in items:
subject = info[2]

Basically, python goes through the elements of items, assigning each one
to the name 'info' during that loop; then in the body of the loop, you
can access the attributes/elements/methods/whatever of the info object.

Hope this helps!

~Ethan~
From: Terry Reedy on
On 6/10/2010 4:47 PM, Anthony Papillion wrote:
> Someone helped me with some code yesterday and I'm trying to
> understand it. The way they wrote it was
>
> subjects = (info[2] for info in items)

This is more or less equivalent to

def _():
for item in items:
yield info[2]
subjects = _()
del _

Terry Jan Reedy


From: Ethan Furman on
Ethan Furman wrote:
> Anthony Papillion wrote:
>> Someone helped me with some code yesterday and I'm trying to
>> understand it. The way they wrote it was
>>
>> subjects = (info[2] for info in items)
>>
>> Perhaps I'm not truly understanding what this does. Does this do
>> anything different than if I wrote
>>
>> for info[2] in items
>> subject = info[2]
>
> Close -- the correct form is
>
> for info in items:
> subject = info[2]
>
> Basically, python goes through the elements of items, assigning each one
> to the name 'info' during that loop; then in the body of the loop, you
> can access the attributes/elements/methods/whatever of the info object.
>
> Hope this helps!
>
> ~Ethan~

Ack. My correction only dealt with the info[2] issue on the for line;
Emille's answer properly matches the original code.

Sorry.

~Ethan~
From: Steven D'Aprano on
On Thu, 10 Jun 2010 15:27:58 -0700, Martin wrote:

> On Jun 10, 11:13 pm, Anthony Papillion <papill...(a)gmail.com> wrote:
>> Thank you Emile and Thomas! I appreciate the help. MUCH clearer now.
>
> Also at a guess I think perhaps you wrote the syntax slightly wrong
> (square brackets)...you might want to look up "list comprehension"


You guess wrong. Python also has generator expressions, which are written
using round brackets instead of square.

In short, the syntax:

it = (expr for x in seq if cond)

is equivalent to:

def generator():
for x in seq:
if cond:
yield expr

it = generator()


except it doesn't create the generator function first.


--
Steven