Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining multiple for loops in Python

Tags:

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 single list.

In multiple lines, solution would be:

arr = []
for article in articles:
    for tag in article.tags:
       arr.append(tag)

Now, how can we write this in single line instead of 4?

This syntax is invalid:

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

Thanks!

like image 249
Zygimantas Avatar asked Nov 28 '22 22:11

Zygimantas


1 Answers

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]
like image 68
Ignacio Vazquez-Abrams Avatar answered Dec 06 '22 14:12

Ignacio Vazquez-Abrams