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 to share