Flattening a shallow list in Python [duplicate]

If you’re just looking to iterate over a flattened version of the data structure and don’t need an indexable sequence, consider itertools.chain and company.

>>> list_of_menuitems = [['image00', 'image01'], ['image10'], []]
>>> import itertools
>>> chain = itertools.chain(*list_of_menuitems)
>>> print(list(chain))
['image00', 'image01', 'image10']

It will work on anything that’s iterable, which should include Django’s iterable QuerySets, which it appears that you’re using in the question.

Edit: This is probably as good as a reduce anyway, because reduce will have the same overhead copying the items into the list that’s being extended. chain will only incur this (same) overhead if you run list(chain) at the end.

Meta-Edit: Actually, it’s less overhead than the question’s proposed solution, because you throw away the temporary lists you create when you extend the original with the temporary.

Edit: As J.F. Sebastian says itertools.chain.from_iterable avoids the unpacking and you should use that to avoid * magic, but the timeit app shows negligible performance difference.

Leave a Comment