yield all entries of an iterable

Stefan Schwarzer sschwarzer at sschwarzer.net
Sun Oct 24 14:58:37 EDT 2010


Hi Sebastian,

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? If you really need an
iterator, you can use `iter(sequence)`:

    >>> my_list = [1, 2, 3]
    >>> i = iter(my_list)
    >>> i.next()
    1
    >>> i.next()
    2
    >>> i.next()
    3
    >>> i.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration

This works at least with Python's built-in sequences (and
dictionaries and sets, but note that these don't have an
obvious order).

Stefan




More information about the Python-list mailing list