Elizabeth Susan Joseph
Elizabeth Susan Joseph

Reputation: 6515

what should I change in my function

list_1  =[1, 2, 3, 4 ]

def fun(list_1):
    for each value in list1:
        # perform some operation and create a new data frame(pandas) for each value in the list
        # so in total I should get 4 data frames.
        print each_value

        return new_data_frame

When I run fun(list_1) I should get 4 data frames:

1
data_frame_1

2
data_frame_2

3
data_frame_3

4
data_frame_4

but I am getting an ouput only with first value.

1
data_frame_1

so what should I change in my function.

Upvotes: 1

Views: 84

Answers (1)

d6bels
d6bels

Reputation: 1482

When you return from the function, it's over.
You're out of the function and that's it.

You could use a generator to achieve what you want or you may return a tuple or a list.


Using a generator :

def fun(list_1):
    for each_value in list_1:
        # perform some operation and create a new data frame(pandas) named "new_data_frame" for each value in the list
        print each_value
        yield new_data_frame

for data_frame in fun(list_1):
    # Do something with the data frame "data_frame"

This will print the value each time, and return your data frame. But it returns a generator, so you have to call the function multiple times. What you cannot really do is get your data frames in a loop without wanting to store them in an list or assimilated or call the function only once.


A simpler way with a list could be:

def fun(list_1):
    data_frames = []
    for each_value in list1:
        # perform some operation and create a new data frame(pandas) named "new_data_frame" for each value in the list
        print each_value
        data_frames.append(new_data_frame)

return data_frames

For reference, I'd suggest you have a look at What does the "yield" keyword do in Python? which may be interesting for you.

Upvotes: 5

Related Questions