PineNuts0
PineNuts0

Reputation: 5234

Python: Assign Flexible Variables That Change Based on Value in Loop

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?

Upvotes: 1

Views: 216

Answers (2)

Timur Shtatland
Timur Shtatland

Reputation: 12347

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

Upvotes: 0

balderman
balderman

Reputation: 23815

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}

Upvotes: 1

Related Questions