Nested iteration?

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Apr 23 18:42:39 EDT 2013


On 23 April 2013 22:41, Joshua Landau <joshua.landau.ws at gmail.com> wrote:
> On 23 April 2013 22:29, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:
>>
>> I just thought I'd add that Python 3 has a convenient way to avoid
>> this problem with next() which is to use the starred unpacking syntax:
>>
>> >>> numbers = [1, 2, 3, 4]
>> >>> first, *numbers = numbers
>
>
> That creates a new list every time. You'll not want that over
> try-next-except if you're doing this in a loop, and on addition (if you were
> talking in context) your method will exhaust the iterator in the outer loop.

Oh, you're right. I'm not using Python 3 yet and I assumed without
checking that it would be giving me an iterator rather than unpacking
everything into a list.

Then the best I can think of is a helper function:

>>> def unpack(iterable, count):
...   iterator = iter(iterable)
...   for n in range(count):
...     yield next(iterator)
...   yield iterator
...
>>> numbers = [1, 2, 3, 4]
>>> first, numbers = unpack(numbers, 1)
>>> first
1
>>> numbers
<list_iterator object at 0x24e1590>
>>> list(numbers)
[2, 3, 4]
>>> first, numbers = unpack([], 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 0 values to unpack


Oscar



More information about the Python-list mailing list