flattening a dict

George Sakkis george.sakkis at gmail.com
Sun Feb 17 10:54:37 EST 2008


On Feb 17, 7:51 am, Arnaud Delobelle <arno... at googlemail.com> wrote:

> BTW, I keep using the idiom itertools.chain(*iterable).  I guess that
> during function calls *iterable gets expanded to a tuple.  Wouldn't it
> be nice to have an equivalent one-argument function that takes an
> iterable of iterables and return the 'flattened' iterable?

Indeed; I don't have any exact numbers but I roughly use this idiom as
often or more as the case where chain() takes a known fixed number of
arguments. The equivalent function you describe is trivial:

def chain2(iter_of_iters):
  for iterable in iter_of_iters:
     for i in iterable:
        yield i

but I usually don't bother, although if it was available in itertools
I'd use it instead.

Apart from introducing a new function for something quite similar,
another idea would be to modify chain(*iterables) semantics if it is
passed a single argument. Currently chain() is useful for 2 or more
arguments; chain(x) is equivalent to iter(x), there's no reason to use
it ever. On the downside, this might break backwards compatibility for
cases like chain(*some_iterable) where some_iterable has length of 1
but I'd guess this is quite rare.

George



More information about the Python-list mailing list