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?

2
  • You cant make your python script write it self. This is what you try to do here Commented Mar 3, 2021 at 20:26
  • I don't know what you mean Commented Mar 3, 2021 at 20:26

2 Answers 2

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} 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.