Question

So I'm currently working with mongoengine, although anything with properties will have the same behavior.

I have a list called collections. Technically it's a mongoengine QuerySet, which is an iterable, but it has virtually all the same behaviors as a list.

Each element collections is an object, with a property called addons which is also a list.

I want to create a flat list of all the addons. Currently doing this produces the desired result

addons = []
for col in collections:
    addons+=col.addons

But when I try this, which I assume is the equivalent list comprehension, I get a list of lists (it essentially appends each list together instead of adding them)

addons = [col.addons for col in collections]

I've been reading about nested list comprehensions and even using itertools but haven't been able to figure out how to get either to work properly

Was it helpful?

Solution

You can use itertools.chain.from_iterable like so:

from itertools import chain
addons = list(chain.from_iterable(col.addons for col in collections))

Available on Python >= 2.6. In the past, it's been quite fast. Faster even than the double list comprehension.

OTHER TIPS

you need a double list comprehension, like:

addons = [item for item in col.addons for col in collections]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top