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!
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With