CS.py
CS.py

Reputation: 43

Store the output of a function into a variable

I have the following function that returns data:

def get_comments():
 for i in data:
  comment_data = i['comments']
  for z in comment_data:
   comments = comment_data['data']
   for j in comments:
    comment = j['message']
    print(comment)

I would like to save the output of this function to a variable. I'm using print instead of return (in the function get_comments) since, return only returns the final row of my data. This is what i have tried to account for that:

def hypothetical(x):
return x

z = hypothetical(get_comments())
print(z)

However the output of the variable z is "None".

When i try some other value(i.e.):

 z = hypothetical(5)
 print(z)

z is equal to 5 of course.
Thanks

Upvotes: 0

Views: 227

Answers (1)

Tom Burrows
Tom Burrows

Reputation: 2365

Instead of printing each line, you need to add it to a different data structure (such as a list) and return the whole list at the end of get_comments().

For example:

def get_comments():
  to_return = []
  for i in data:
    comment_data = i['comments']
    for z in comment_data:
      comments = comment_data['data']
      for j in comments:
        comment = j['message']
        to_return.append(comment)
  return to_return

If you want to get a bit more advanced, you can instead create a generator using yield:

def get_comments():
  for i in data:
    comment_data = i['comments']
    for z in comment_data:
      comments = comment_data['data']
      for j in comments:
        comment = j['message']
        yield comment

Then you can iterate over get_comments() and it will go back into the generator each time to get the next comment. Or you could simply cast the generator into a list with list(get_comments()) in order to get back to your desired list of comments.

Refer to this excellent answer for more about yield and generators.

Upvotes: 5

Related Questions