On 23 April 2013 22:41, Joshua Landau <joshua.landau...@gmail.com> wrote: > On 23 April 2013 22:29, Oscar Benjamin <oscar.j.benja...@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 -- http://mail.python.org/mailman/listinfo/python-list