yield all entries of an iterable

Cameron Simpson cs at zip.com.au
Mon Oct 25 01:08:30 CEST 2010

On 24Oct2010 20:58, Stefan Schwarzer <sschwarzer at sschwarzer.net> wrote:
| On 2010-10-21 00:27, Sebastian wrote:
| > Is there a simpler way to yield all elements of a sequence than this?
| > for x in xs:
| >     yield x
| Can you give an example where you would need this? Can't
| you just iterate over the sequence?

The usual example is when the sequence comes from inside.
Example, closely resembling some code from on of my projects:

  def leaves(N):
    if N.isleaf:
      yield N
    for subN in N.subnodes:
      for leaf in leaves(subN):
        yield leaf

which walks a tree structure returning leaf nodes.

The point is that you're calling leaves() on the subnode and yiled them
directly to the outside. The caller may not even know there are "subnodes".

Cameron Simpson <cs at zip.com.au> DoD#743

The Borg assimilated my race and all I got was this lousy tagline.
        - Cath Lawrence <Cath_Lawrence at premium.com.au>

More information about the Python-list mailing list