How to get the n next values of a generator in a list (python)

Peter Smit picture Peter Smit · Nov 11, 2010 · Viewed 13.9k times · Source

I have made a generator to read a file word by word and it works nicely.

def word_reader(file):
    for line in open(file):
        for p in line.split():
            yield p

reader = word_reader('txtfile')
next(reader)

What is the easiest way of getting the n next values in a list?

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Nov 11, 2010

Use itertools.islice:

list(itertools.islice(it, n))