Need help-variable in Python

I want to create variables as a1

, a2

, a3

... a10

. I used a for loop for this. As a variable in the loop increments, I need to create a variable as above.

Can someone give me an idea?

During creation, I also need to be able to assign values ​​to them.

What I am getting a syntax error.

-1


source to share


4 answers


Following what S.Lott said, you can also use a dict if there are truly unique names and that the order of the elements is not important:

data = {}
for i in range(0, 10):
  data['a%d' % i] = i

>>>data
{'a1': 1, 'a0': 0, 'a3': 3, 'a2': 2, 'a5': 5, 'a4': 4, 'a7': 7, 'a6': 6, 'a9': 9, 'a8': 8}

      



I would add that it is very dangerous to automate the creation of variables the way you want, as you can overwrite already existing variables.

+4


source


We usually use a list rather than a bunch of individual variables.



a = 10*[0]
a[0], a[1], a[2], a[9]

      

+13


source


globals()

returns a global dictionary of variables:

for i in range(1,6):
    globals()["a%i" % i] = i

print a1, a2, a3, a4, a5      # -> 1 2 3 4 5

      

But honestly: I would never do that, polluting the namespace automatically is harmful. I would rather use a list or dict.

+2


source


You can use exec function:

for i in range(0,10):
   exec("a%d=%d" % (i,i))

      

Not a very pythonic way of doing things.

-1


source







All Articles