Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list comprehension returning "generator object..."

I'm trying to succinctly create a list from a dictionary.

The following code works:

def main():
    newsapi = NewsApiClient(api_key=API_KEY)
    top_headlines = newsapi.get_everything(q="Merkel",language="en")
    news = json.dumps(top_headlines)
    news = json.loads(news)
    articles = []
    for i in news['articles']:
        articles.append(i['title'])
    print(articles)

output:

['Merkel “Helix Suppressor” Rifle and Merkel Suppressors', 'Angela Merkel', 
 'Merkel says Europe should do more to stop Syria war - Reuters', 
 'Merkel says Europe should do more to stop Syria war - Reuters', 
 'Merkel muss weg! Merkel has to go! Demonstrations in Hamburg', ... , 
 "Bruised 'Queen' Merkel Lives..."]

But I've seen elsewhere, and been trying to learn, list comprehension. Replacing the for i in news['articles']: loop with:

def main():
    ...
    articles = []
    articles.append(i['title'] for i in news['articles'])
    print(articles)

I was expecting to get a similar output. Instead it returns:

[<generator object main.<locals>.<genexpr> at 0x035F9570>]

I found this related solution but doing the following outputs the titles (yay!) three times (boo!):

def main():
    ...
    articles = []
    articles.append([i['title'] for x in news for i in news['articles']])
    print(articles)

What is the correct way to generate the articles via list comprehension?

Ignore that I have routines in main() instead of calls to functions. I will fix that later.

like image 797
BruceWayne Avatar asked May 23 '18 17:05

BruceWayne


2 Answers

Just use:

articles = [i['title'] for i in news['article']]

The list comprehension already return a list, so there is no need to create an empty one and then append values to it. For a gide on list comprehensions you may check this one.

Regarding the generator object, the issue here is that using list comprehensions between () (or simply when they are not enclosed) will create a generator instead of a list. For more info on generators and how are they different than lists, see Generator Expressions vs. List Comprehension and for generator comprehentions, see How exactly does a generator comprehension work?.

like image 116
OriolAbril Avatar answered Nov 08 '22 00:11

OriolAbril


Replace:

articles.append(i['title'] for i in news['articles'])

with:

articles+=[i['title'] for i in news['articles']]
like image 38
Tomato Master Avatar answered Nov 08 '22 00:11

Tomato Master