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’:
- if Condition is set to false, the loop ends without having to
breakout of the for loop.- an extension of the above reasons, methods with access to Condition can end the loop without going over all other items in the said list, or implementing a special check in the for loop.
- The first approach allows skipping items in the loop, should the need arise.
- There is also one less level of indentation. This is more vanity then anything else, but considering that the actual code was part of a class method, the indent level was already pretty high.
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.
I’d suggest you use some iterators
iter(callable, sentinel)returns an iterator which produces the result of callable() until it return sentinel.itertools.chain.from_iterablereturns 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.