SingularityCat
SingularityCat

Reputation: 38

Python nested for loop Vs generator for repeatedly iterating over a list provided by a function

The problem is quite simple, I have a method that returns a list. I want to iterate over every item in this list, and once finished, call the method to receive a new list, and repeat.

At the moment, my code looks something like:

generator = iter([])
while Condition:
    try:
        item = next(generator)
    except StopIteration:
        generator = iter(list_returining_method())
        item = next(generator)
    ...

However, previously, I was using a nested for loop.

while Condition:
    for item in list_returining_method():
        ...

While my previous attempt looks nicer in some respects, but my current method has some 'advantages':

To say the least, im confused as to which is more appropriate. They both seem to have unique advantages and disadvantages, so if anyone knows the most correct and pythonic approach, I'd really appreciate it.

Upvotes: 2

Views: 2109

Answers (2)

Winston Ewert
Winston Ewert

Reputation: 45039

I'd suggest you use some iterators

items = itertools.chain.from_iterable( iter(list_returning_method, None) )

for item in items:
    # do something with item
    print item

    if not Condition:
       break

iter(callable, sentinel) returns an iterator which produces the result of callable() until it return sentinel.

itertools.chain.from_iterable returns an iterator that flattens the original iterator, it will produce the values in the lists produced by the first iterator.

I think that gives you most of the advantages of your method but with a cleaner style.

Upvotes: 2

wberry
wberry

Reputation: 19347

There is room for opinion here, but the brevity of the second approach makes it a clear win as far as I'm concerned. Especially if the use of the item variable is limited to within the loop, I would choose the for / in syntax every time. There have been some problems, involving buffers and state changes within a loop, where I have chosen not to use for / in. But that is a small minority.

Upvotes: 1

Related Questions