Search code examples
pythonlistgenerator

How to get the n next values of a generator into a list


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 into a list?


Solution

  • Use itertools.islice:

    list(itertools.islice(it, n))