Questions: While And List Comprehension

Chris Rebert clp2 at rebertia.com
Wed Nov 10 21:18:09 EST 2010


On Wed, Nov 10, 2010 at 5:38 PM, MRAB <python at mrabarnett.plus.com> wrote:
> On 11/11/2010 00:29, James Mills wrote:
>> On Thu, Nov 11, 2010 at 8:56 AM, Emile van Sebille<emile at fenx.com>  wrote:
>>> Easiest would be print [ v for v in sys.stdin.readlines()[:5] ] but that
>>> still reads the entire sys.stdin (whatever it may be...)
>>
>> Here's a way of doing the same thing without consuming the entire
>> stream (sys.stdin):
>>
>> #!/usr/bin/env python
>>
>> import sys
>> print [v for v in list(line for line in sys.stdin)[:5]]
>>
>> This uses a generator expression to read from stdin, converts this to
>> a list (only getting the first 5 items).
>>
> 'list' will exhaust the input, then the slicing will return at most 5
> lines.

Also, the list comprehension and generator expression are both the
identity versions thereof, so a shorter equivalent version of the
erroneous code would be simply:
print list(sys.stdin)[:5]

Cheers,
Chris



More information about the Python-list mailing list