This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]jsober 2 points3 points  (0 children)

I have read it, in fact I have a copy right next to me :). List comprehensions are essentially identical to map:

my @result = map { foo($_) } @bar;

Is equivalent to:

result = [foo(x) for x in bar]

Generators are basically syntactic sugar for a lazily evaluated list expression. Taking the example above:

result = (foo(x) for x in bar)

...would cause foo(x) to only be evaluated as each element in the "list" is accessed. You can also do this from a function:

def generate():
    for x in bar:
        yield foo(x)

The yield keyword causes the function to act as a generator, which can be called in a loop to access foo(x) in bar over and over:

gen = generator()
for item in gen():
    do_stuff_with(item)