On Thu, 21 Apr 2016 05:34 am, Ken Seehart wrote: > Currently the common pattern for yielding the elements in a sequence is as > follows: > > for x in sequence: yield x > > I propose the following replacement (the result would be identical): > > yield *sequence
Others have already pointed out that this already exists as "yield from iter(sequence)", but I'd like to say that this syntax was not added merely to shorten the "for x in sequence: yield x" idiom. In its simplest case, "yield from expr" is equivalent to "for x in expr: yield x", and it is completely reasonable to use it for such simple purposes. But that's not why it was added to the language, and if that's *all* it did, it probably wouldn't have been. Rather, "yield from" was added to support the full set of generator behaviour, including their send(), close() and throw() methods. That makes "yield from expr" equivalent to this rather formidable chunk of code: _i = iter(EXPR) try: _y = next(_i) except StopIteration as _e: _r = _e.value else: while 1: try: _s = yield _y except GeneratorExit as _e: try: _m = _i.close except AttributeError: pass else: _m() raise _e except BaseException as _e: _x = sys.exc_info() try: _m = _i.throw except AttributeError: raise _e else: try: _y = _m(*_x) except StopIteration as _e: _r = _e.value break else: try: if _s is None: _y = next(_i) else: _y = _i.send(_s) except StopIteration as _e: _r = _e.value break RESULT = _r See PEP 380 for more info: https://www.python.org/dev/peps/pep-0380/ -- Steven -- https://mail.python.org/mailman/listinfo/python-list