A discussion on python-dev ( http://mail.python.org/pipermail/python-dev/2002-November/030380.html ) came up with the idea of allowing arbitrary assignments::
>>> a,b,*c = (1,2,3,4,5) >>> a 1 >>> b 2 >>> c (3, 4, 5)
I didn't like the idea of adding this to the language for assignments, so I came up with a generator that basically does the above but assigns the last variable the used iterator, and all without any new syntax.
Thanks to Alex Martelli for simplifying the code and Oren Tirosh for coming up with better variable names.
1 2 3 4 5 6 7 8 9
def peel(iterable, arg_cnt=1): """Use ``iterable`` to return ``arg_cnt`` number of arguments plus the iterator itself. """ iterator = iter(iterable) for num in xrange(arg_cnt): yield iterator.next() yield iterator
So now you can do the same as the example mentioned previously as::
>>> a,b,c = peel((1,2,3,4,5), arg_cnt=2) >>> a 1 >>> b 2 >>> c >>> for value in c: print value 3 4 5
This of course works for as many arguments as you want; just make sure you set arg_cnt properly and that the iterable can be called that many times.