4 ms·
Or, in Python 3.3 and above: class Stuff: def __init__(self): self.a_list = [1,2,3,4] def __iter__(self): yield from self.a_list
by danudey 5y ago
Or, in Python 3.3 and above:
class Stuff:
def __init__(self):
self.a_list = [1,2,3,4]
def __iter__(self):
yield from self.a_list
- remram 5y agoCan't you just: def __iter__(self): return iter(self.a_list)
- necovek 5y agoI was not trying to go for the shortest code, but to show idiomatic code where you could easily do something else instead of just returning same values (otherwise, there is no value in wrapping a list with a class at all). With both `iter(self.a_list)` or `yield from` you'd have to add a list comprehension in there to process each element, and with no Ruby-like blocks in Python, that limits what one can do. But they are both definitely good approaches to highlight!
- remram 5y agoYou mean generator, not list comprehension. Either way, you wouldn't `yield from` a list comprehension, you'd just use a loop. E.g. why write: yield from (a*2 for a in self.a_list) When you can: for a in self.a_list: yield a*2
- necovek 5y agoExactly, that's the reason I used a loop in the original snippet :)