Where is the usage of (list comprehension) documented?

Chris Angelico rosuav at gmail.com
Sun Jan 14 18:05:44 EST 2018


On Mon, Jan 15, 2018 at 10:01 AM, Peng Yu <pengyu.ut at gmail.com> wrote:
> Hi,
>
> I see the following usage of list comprehension can generate a
> generator. Does anybody know where this is documented? Thanks.
>
> $ cat main.py
> #!/usr/bin/env python
>
> import sys
> lines = (line.rstrip('\n') for line in sys.stdin)
> print lines
>
> lines = [line.rstrip('\n') for line in sys.stdin]
> print lines
> $ seq 10 | ./main.py
> <generator object <genexpr> at 0x1101ecd70>
> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
>

When you use square brackets, you're creating a generator, as in your
second example. Your first example is a slightly different beast
called a "generator expression". If you search for that in the docs or
on the web, you'll find what you want.

ChrisA



More information about the Python-list mailing list