[Tutor] don't understand iteration

eryksun eryksun at gmail.com
Tue Nov 11 15:19:35 CET 2014

On Tue, Nov 11, 2014 at 4:52 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 11/11/14 04:45, Clayton Kirkwood wrote:
>>>> *list(range(1,6))
>>    File "<input>", line 1
>> SyntaxError: can use starred expression only as assignment target
> list() is a function. You cannot unpack a function.
> Also the * operator needs to be used inside a function parameter list.
> (There may be some obscure case where you can use it outside of that but 99%
> of the time that's the only place you'll see it used.)

Python 3 extended unpacking:

    >>> a, *bcd, e = 'abcde'
    >>> a
    >>> bcd
    ['b', 'c', 'd']
    >>> e

    >>> for x, *rest in ('abc', 'de'):
    ...     print(x, rest)
    a ['b', 'c']
    d ['e']

>>>>> a = list(range(*5))
> And here 5 is an integer. It must be a sequence.

Any iterable suffices.

Refer to the table in section 8.4.1 for an overview of container interfaces:

A common non-sequence example is unpacking a generator:

    >>> gen = (c.upper() for c in 'abcde')
    >>> print(*gen, sep='-')

A generator is an iterable:

    >>> gen = (c.upper() for c in 'abcde')
    >>> type(gen)
    <class 'generator'>

    >>> hasattr(gen, '__iter__')
    >>> isinstance(gen, collections.Iterable)

and also an iterator:

    >>> hasattr(gen, '__next__')
    >>> isinstance(gen, collections.Iterator)

    >>> it = iter(gen)
    >>> it is gen

    >>> next(it), next(it), next(it), next(it), next(it)
    ('A', 'B', 'C', 'D', 'E')
    >>> next(it)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>

More information about the Tutor mailing list