Gian L Gian L - 1 month ago 7
Python Question

Store the result of a function with loop in a variable

This is probably a very basic question, I have to store the results of a for loop in a variable, but somehow this does not seem to work:

import ystockquote
import numpy as np


I define a vector of stocks

df = pd.DataFrame(np.array(['OXLC','CG','NYMT', 'MMLP','CMFN','PNNT']), columns=['Ticker'])


I use a loop to get the dividends of these stocks:

def func1(df):
for x in df['Ticker']:
return ystockquote.get_dividend_per_share(x)


I store the result of the function in the variable "dividends", but for some reason in the variable dividends I only find the dividend of the first stock appearing in the vector:

dividends = func1(df)
print(dividends)


Does anyone understand why this happens?

Answer

return returns immediately from the function. So the first iteration of your loop is happening, but as soon as you reach the return statement, it returns that value. One solution is to collect up your results in a list and then return that:

def func1(df):
    results = []
    for x in df['Ticker']:
        results.append(ystockquote.get_dividend_per_share(x))
    return results

For this simple of a loop, you might consider list comprehension instead:

def func1(df):
    return [ystockquote.get_divident_per_share(x) for x in df['Ticker']]
Comments