1
def my_func(arg):
    ...
    x = foo(var_arg)
    ...

With many variables saved as var_1, var_2, var_3 I would be able to pass one of them based on the foo function's argument. So if I call my_func(2), in the function x will equal the result of foo(var_2). Is it possible to construct a variable name like you would with strings?

kmario23
  • 57,311
  • 13
  • 161
  • 150
AlexT
  • 589
  • 2
  • 9
  • 23
  • Possible duplicate of: https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables – Justin Wager Oct 12 '18 at 01:45
  • Not exactly @JustinWager. The OP seems to already have the variables. They just need a good way to pair certain variables with certain options. – Christian Dean Oct 12 '18 at 01:46

2 Answers2

2

How about using a dictionary for storing the variables and then dynamically constructing variable names based on the arguments passed and then accessing the corresponding values, which can then be passed on as argument to function foo

In [13]: variables = {"var_1" : 11, "var_2": 22, "var_3": 33} 
    ...:  
    ...: def my_func(arg): 
    ...:     full_var = "var_" + str(arg)
    ...:     print(variables[full_var])
    ...:     # or call foo(variables[full_var])    
In [14]: my_func(1)                                                      
11

In [15]: my_func(2)
22

In [16]: my_func(3)
33
kmario23
  • 57,311
  • 13
  • 161
  • 150
1

What I recommend you do is to use dictionaries. In my view, that would be the most efficient option. For example, pretend var_1, var_2, and var_3 equal 'a', 'b', and 'c' respectively. You'd then write:

d = {1: 'a', 2: 'b', 3: 'c'}

def foo(var):
    return d[var]

def my_func(arg):
    x = foo(var_arg)
    return x

my_func(1) # returns: 'a'

As you can see, you really don't even need variables when using the dictionary. Just use the value directly.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87