Skip to content Skip to sidebar Skip to footer

Combining Multiple For Loops In Python

Let's say, we have and list of objects in variable called 'articles', each object has a member 'tags' (which is simple list). Expected output: all tags in all articles, joined in a

Solution 1:

It's invalid because article doesn't exist by the time the first loop is parsed.

arr = [tag for article in articles for tag in article.tags]

Solution 2:

You are actually looping in the order that you don't want to order:

what you want is:

result = [ tag for article in articles for tag in article.tags ]

To translate what you were doing in your example would be:

fortaginarticle.tags:
    forarticleinarticles:
       #code

which doesn't make much sense.

Solution 3:

Perhaps

arr = [tag for tag in (a.tags for a in articles)]

Solution 4:

Try this:

import itertools
it = itertools.chain.from_iterable(article.tags for article in articles)
l  = list(it) # if you really need a list and not an iterator

Solution 5:

This is already answered multiple times, but it can be helpful to break lines and indent:

arr = [tag 
       for article in articles
           for tag in article.tags]

This has the advantage of

  1. Making it more readable if you needed to do some kind of projection on tag (like getting (tag.name, tag.description, tag.count) or some other tuple or transformation of a tag)
  2. Making the syntax for nested generator expressions more readable to a beginner
  3. Making complex nested generator expressions more readable

Post a Comment for "Combining Multiple For Loops In Python"