0

Say I have a function, denoted by Show, that runs by accessing points in a list. Is it then possible to assign each outcome from the function to a variable? Is it possible for the variable to be defined by dfi so the outputs would be df1, df2, df3, ect... for a long as defined by count?

count = 5
for i in range(0, count):
    d = Show(list[i])
0

2 Answers 2

2

Dynamic naming could be achieved by using advanced Python features not recommended for normal use (see for instance Dynamically set local variable).

If you know the number of elements in advance, you can do

df1, df2, df3, df4, df5 = [Show(list[i]) for i in range(5)]

If you don't, you're probably better off using a list to store the results.

count = 5
d = []
for i in range(0, count):
    d.append(Show(list[i]))

which can be more elegantly written

d = [Show(list[i]) for i in range(count)]

or even a dictionary

d = [f"df{i}": Show(list[i]) for i in range(count)]
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this using a dict by storing variables as keys. A sample could be like this:

count = 5
dic = {}
for i in range(count):
  #create key, that would be the variable
  k = "df{}".format(i)
  dic[k] = show(list[i])

And now you can use dict to fetch and use the variables in O(1) which would be same as if you have defined the variables explicitly and stored them.

2 Comments

The function runs okay with this method but then when I try to draw say df1 outside of the loop it says df1 is not defined
You have to call dic['df1'] to get df1, as it is stored in the dic as a key. You can read more about python dictionaries here to get started if this is new to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.