I would like to have yield variable number of elements that would allow me to write a generator function of the following type:
x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] def multi_enumerate(*iterables): n = 0 iterators = map(iter, iterables) while iterators: yield n, *tuple(map(next, iterators))
Does anyone know how to do this? I know that I can get a tuple, but for this I need to explicitly unpack it on the receiving side, for example: a,b,c = t[0], t[1], t[2] .
Final decision :
FWIW, this is what I ended up using, based on a comment by John Kugelman:
from itertools import izip def multi_enumerate(*iterables, **kwds): start = kwds.get('start') if start is None: if kwds: raise TypeError( "multi_enumerate() accepts only the keyword argument 'start'") try: iter(iterables[-1])
The added code, because of my desire to also force it to accept an optional non-iterable last argument, to indicate an initial value other than 0 (or specify it using the start keyword argument), as well as the built-in enumerate() .
source share