2

Let's say I need to make 5 variables. Since this may need to be adjusted in the future, I'm using a loop.

i = 0
for j in range(5):
    i += 1
    w[i] = function(i)

#results in:
    w1 = function(1)
    w2 = function(2)
    #etc...

I know the code above is incorrect. Is it possible to use a loop to create different variables?

martineau
  • 112,593
  • 23
  • 157
  • 280
i..
  • 158
  • 1
  • 2
  • 6
  • 2
    What's wrong with just using a list? – user94559 Oct 06 '17 at 14:10
  • hard to store a numpy array in a list and not get too complicated quickly, that's why I need individual vars. – i.. Oct 06 '17 at 14:16
  • Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – wjandrea Jul 02 '20 at 01:29

3 Answers3

4

To create multiple variables you can use something like below, you use a for loop and store a pair of key-value, where key is the different variable names

    d={} #empty dictionary
    for x in range(1,10): #for looping 
        d["string{0}".format(x)]="Variable1"

The output looks like

{'string1': 'Variable1', 'string2': 'Variable1','string3': 'Variable1', 'string4': 'Variable1', 'string5':'Variable1', 'string6': 'Variable1', 'string7': 'Variable1','string8': 'Variable1', 'string9': 'Variable1'}
Chetan_Vasudevan
  • 2,354
  • 1
  • 11
  • 32
3

You can create actual variables, but don't. Use a list

W = []
for j in range(5):
    ...
    W.append(function(i))
BioGeek
  • 20,793
  • 21
  • 79
  • 136
blue_note
  • 25,410
  • 6
  • 56
  • 79
1

You'd better just use a list. It's more readable and safer.
However, you can create variables in the global namespace using globals() dictionary:

i = 0
for j in range(5):
    i += 1
    globals()["w" + str(i)] = function(i)

Use it like this:

print (w1)

However, that's probably not a good idea. You can accidentally override something in the namespace, which will cause hard to debug bugs. Really, try not to do that.

If you want to call them by name and not by index (as in a list), use your own dictionary:

my_variables = {}
i = 0
for j in range(5):
    i += 1
    my_variables["w" + str(i)] = function(i)

Then use like this:

print (my_variables["w1"])
Neo
  • 3,164
  • 2
  • 17
  • 32