Questions: While And List Comprehension

Steve Holden steve at holdenweb.com
Thu Nov 11 04:02:51 CET 2010


On 11/10/2010 7:29 PM, 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).
> 
A generator expression slicing only accesses as many elements as it
needs to? But surely list(line for line in sys.stdin) will be evaluated
before the indexing is applied?

I'd have thought that would have exhausted the input file.

>>> f = open("/tmp/data", "w")
>>> for i in 'one two three four five six seven eight nine ten'.split():
...     f.write("%s\n" % i)
...
>>> f.close()
>>> f = open("/tmp/data")
>>> print [v for v in list(line for line in f)[:5]]
['one\n', 'two\n', 'three\n', 'four\n', 'five\n']
>>> f.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

This suggests that you are mistaken about not exhausting the source.

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17       http://us.pycon.org/
See Python Video!       http://python.mirocommunity.org/
Holden Web LLC                 http://www.holdenweb.com/




More information about the Python-list mailing list