15.07.2013 12:40, Oscar Benjamin wrote:
first_line = next(inputfile) # inspect first_line for line in chain([first_line], inputfile): # process line
could be rewritten as
first_line = next(inputfile): for line in first_line, *inputfile: pass
without reading the whole file into memory.
Please note, that with PEP 448 syntax you could express it by: first_line = next(inputfile) for line in (*it for it in ([first_line], inputfile)): ... Event now, in Python 3.3, you can[*] write: first_line = next(inputfile) for line in [(yield from it) for it in [[first_line], inputfile]]: ... Cheers, *j [*] Please note that it is `yield from` within a *list comprehension*, not a generator expression... And that this list cimprehension still evaluates to a *generator*, not a list! (a [None, None] list is set as StopIteration's value when the generator is exhausted) An interesting fact (but understandable after a though) is that: while a generator created with: [(yield from it) for it in [[1,2,3], 'abc']] produces items: 1, 2, 3, 'a', 'b', 'c', a generator created with: ((yield from it) for it in [[1,2,3], 'abc']) produces items: 1, 2, 3, None, 'a', 'b', 'c', None I am not sure if ability to use it that way is only an implementation artifact, but it works.