0

Still trying to wrap my head around list comprehensions. Below, 'e' is a list. How would I write this as a list comprehension?

events = []
        for req in request:
            e = req[attr]
            events.extend(e)

I tried the following and it gave me a list of lists([[a,b],[c,d]] rather than a flat list [a, b, c, d]

events = [req[attr] for req in request]
nebula186
  • 119
  • 2
  • 14
  • ```events = [val for req in request for val in req[attr]]```? –  Aug 06 '21 at 17:56
  • this is definitely a duplicate https://stackoverflow.com/a/3899658/14385360 – Einliterflasche Aug 06 '21 at 17:58
  • 2
    Does this answer your question? [list.extend and list comprehension](https://stackoverflow.com/questions/3899645/list-extend-and-list-comprehension) – Einliterflasche Aug 06 '21 at 18:00
  • 1
    You said you want a "flat list"; searching for `list comprehension flatten` [gives you multiple good answers right off the top, without even mentioning Python](https://duckduckgo.com/?q=list+comprehension+flat). – Karl Knechtel Aug 06 '21 at 18:02
  • Please also specifcially see https://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/ – Karl Knechtel Aug 06 '21 at 18:03

1 Answers1

1

You can use two generators in the list comprehension:

events = [val for req in request for val in req[attr]]
chepner
  • 497,756
  • 71
  • 530
  • 681