1

I have a list: test = ['0to50', '51to100', '101to200', '201to10000']

I want to create the following four variables using a for loop:

var_0to50
var_51to100
var_101to200
var_201to10000

I tried the following code:

test = ['0to50', '51to100', '101to200', '201to10000']

for i in test:
    print (i)

    var_{i} = 3

But it gives me error:

File "<ipython-input-76-58f6edb37b90>", line 6
    var_{i} = 3
        ^
SyntaxError: invalid syntax

What am I doing wrong?

PineNuts0
  • 4,740
  • 21
  • 67
  • 112

2 Answers2

1

You can have a dict

test = ['0to50', '51to100', '101to200', '201to10000']
d = {x: 3 for x in test}
print(d)

output

{'0to50': 3, '51to100': 3, '101to200': 3, '201to10000': 3}
balderman
  • 22,927
  • 7
  • 34
  • 52
0

It is likely that you need a dictionary, instead of several dynamically named variables:

test = ['0to50', '51to100', '101to200', '201to10000']
dct = {}

for k in test:
    print(k)
    dct[k] = 3

print(dct)
    
# 0to50
# 51to100
# 101to200
# 201to10000
# {'0to50': 3, '51to100': 3, '101to200': 3, '201to10000': 3}

SEE ALSO:
How do I create variable variables?
Creating multiple variables

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47