Questions: While And List Comprehension

James Mills prologic at
Thu Nov 11 01:29:04 CET 2010

On Thu, Nov 11, 2010 at 8:56 AM, Emile van Sebille <emile at> 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).


-- James Mills
-- "Problems are solved by method"

More information about the Python-list mailing list