Home > OS >  How to store multiple results from a function in a for loop as unique variables in Python?
How to store multiple results from a function in a for loop as unique variables in Python?

Time:12-19

I have a function that returns different values based on different inputs. I want it to go through a list, spitting out results for each input. But then I don't know how to store each of those results as a unique variable...

Here's an example of the list

list = ["input1", "input2", "input3"]

The function returns a different integer depending on the input. I'm going through the list with a for loop like so

for input in list:
    my_function(input)

The function in the loop runs for each item in the list and returns a unique integer for each. But how do I store each of the returned values as their own variable?

I've tried this. But it overwrites the variable each time and only leaves me with the last one in the loop

for input in list:
    var = my_function(input)

Is there some way to dynamically change that variable in each run through the loop?

CodePudding user response:

vars = []
for input in list:
    vars.append(my_function(input))

or

vars = [my_function(input) for input in list]

or the dictionary approach

vars = {}
for input in list:
    vars[input] = my_function(input)

or the inline

vars = {input: my_function(input) for input in list} 

CodePudding user response:

I'd like to know why you're trying to achieve what you're trying to achieve, it sounds like a terrible idea, what you want seems to be another list or dictionary.

With that being said, I wouldn't recommend it but this snippet of code might do the trick.

ctr = 0


def my_function(inp):
    return f"RETURN VAL OF MY FUNCTION FOR INPUT {inp}"

lst = ["input1", "input2", "input3"]

for i in lst:
    exec(f'var{ctr 1} = "{my_function(i)}"')
    ctr =1

print(var1)
print(var2)
  • Related