pythonfor-looplist-comprehensionstopiteration

How do I prevent my list comprehension from raising a stopIteration error


I'm stepping through a text file with records that are 3-lines long. If, in the first line, I can say "this is a record that I don't want to count", I want to move to the start of the next record, 2 lines further down. Currently, I'm running a code snippet like this:

lines = content.split("\n")
iterable = iter(xrange(len(lines)))
for i in iterable:
    line = lines[i]
...
    if isRecord(keyword) == False:
        [iterable.next() for x in range(2)]

At the very end of the file, there's a chance that my comprehension'll kick out a stopIteration error. How do I add to my code so that if I raise a stopIteration, that it'll break the for loop? I've looked at a number of entries on list comprehensions, along with how the for-loops are built to stop based on the stopIteration flag, but I don't yet understand how to apply that to my own code. I've also seen list comprehensions with an if/else/for style, but can I build one that has a style like:

[iterable.next() for x in range(2) else break]

Thanks for all of the help, sincerely.


Solution

  • You can take a slice using itertools. some_list will be length 2, 1 or 0, depending on how much of the list remains. If the list is larger, 2 items will be removed from the iterator and the for loop will continue with the next item.

    import itertools
    
    lines = content.split("\n")
    iterable = iter(xrange(len(lines)))
    for i in iterable:
        line = lines[i]
    ...
        if isRecord(keyword) == False:
            some_list = list(itertools.islice(iterable, 2))