Python nested for loops using list comprehension

2529 views python

for module in host.modules:
    for removal in removal_re:
        compile_re = re.compile(removal)
        if compile_re.match(

How am I able to do the above using list comprehension? I've tried researching a lot on list comp but can't seem to get my head around it for some reason. Any ideas/suggestions?

answered question

Just a comment: List comprehensions aren't per sei better than for loops. From the Zen of Python: Simple is better than complex.

1 Answer


Like this:

res = [next((removal for removal in removal_re if re.compile(removal).match(, 'N\A')) for module in host.modules]

but I would stick to the explicit for loops. The comprehension version is simply too long.

Also note that I could not test the above for obvious reasons.

posted this

Have an answer?


Please login first before posting an answer.