Search code examples
pythoniteratorlist-comprehensionstopiteration

Python: StopIteration exception and list comprehensions


I'd like to read at most 20 lines from a csv file:

rows = [csvreader.next() for i in range(20)]

Works fine if the file has 20 or more rows, fails with a StopIteration exception otherwise.

Is there an elegant way to deal with an iterator that could throw a StopIteration exception in a list comprehension or should I use a regular for loop?


Solution

  • You can use itertools.islice. It is the iterator version of list slicing. If the iterator has less than 20 elements, it will return all elements.

    import itertools
    rows = list(itertools.islice(csvreader, 20))