Python nested for loops using list comprehension

2529 views python
9

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

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

13

Like this:

res = [next((removal for removal in removal_re if re.compile(removal).match(module.name), '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?

JD

Please login first before posting an answer.