I have a simple question of beginner.
How to make this code work :
variable0 = 0
...
variable9 = 9
I tried :
for j in range(9):
variable"{}".format(j) = j
and others similar things with eval() and exec() functions.
Thanks a lot !
I have a simple question of beginner.
How to make this code work :
variable0 = 0
...
variable9 = 9
I tried :
for j in range(9):
variable"{}".format(j) = j
and others similar things with eval() and exec() functions.
Thanks a lot !
Why not use a list instead, together with list comprehension:
variable = [i for i in range(10)]
Then you could use variable[0]
for your "variable0", etc.
Or, as mentioned in a few comments
variable = list(range(10))
If you really want to do this you can do:
for j in range(9):
exec("variable{} = j".format(j))
But as others have said, you probably shouldn't.
If you're using numbers, use a list:
items = [1, 2, 3, 4, ...]
or
items = range(10)
then you can look up items[0]
, items[2]
, etc
If you want to use something else to identify items, use a dictionary:
items = {
1: 1,
2: 2,
'foo': 'bar'
...
}
You can look up with items[0]
, items['foo']
, etc
You can also use list comprehension or dictionary comprehension to define your data structures, e.g.
items = {i: i for i in range(10)}
I think the use of a dictionary is better suited for this task:
d = {"variable{}".format(i): i for i in range(10)}
print(d['variable0']) # ==> 0
print(d['variable5']) # ==> 5
print(d['variable9']) # ==> 9
If you really, really need this specific behaviour (changing variable names on the fly) there is a way to acomplish it. I don't recommend this solution, since there are more intuitive ones and this approach is not a very good design. Here it is:
l = locals()
counter = 0;
for i in range(9):
l["variable" + str(counter)] = i
counter += 1
I wouldn't really recommend this but you could assign the globals() or locals() dictionaries depending on whether you're doing this at the module level or within a function.
for i in range(10): globals()[f'variable{i}'] = 0
def myfunc():
for i in range(10): locals()[f'variable{i}'] = 0