Sure you can; it's called a dictionary:
d = {}
for x in range(1, 10):
d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
'string2': 'Hello',
'string3': 'Hello',
'string4': 'Hello',
'string5': 'Hello',
'string6': 'Hello',
'string7': 'Hello',
'string8': 'Hello',
'string9': 'Hello'}
I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!
Answer from the wolf on Stack OverflowSure you can; it's called a dictionary:
d = {}
for x in range(1, 10):
d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
'string2': 'Hello',
'string3': 'Hello',
'string4': 'Hello',
'string5': 'Hello',
'string6': 'Hello',
'string7': 'Hello',
'string8': 'Hello',
'string9': 'Hello'}
I said this somewhat tongue in check, but really the best way to associate one value with another value is a dictionary. That is what it was designed for!
It is really bad idea, but...
for x in range(0, 9):
globals()['string%s' % x] = 'Hello'
and then for example:
print(string3)
will give you:
Hello
However this is bad practice. You should use dictionaries or lists instead, as others propose. Unless, of course, you really wanted to know how to do it, but did not want to use it.
Is it possible to create variables in a loop?
Why does everyone teach FOR LOOPS with the same variable name?
Using a loop in Python to name variables - Stack Overflow
Changing variable names with Python for loops - Stack Overflow
Videos
I need to create a large number of variable. Currently what I have is:
var1 = 0 var2 = 0 ... var1000 = 0
Is it possible to create these variables in some sort of loop instead of writing each one?
#Pseudocode
for i in range(1000):
var_i = 0Update:
Thanks a lot for all the comments! The list idea worked!
I'm trying to learn for loops but it feels like everyone teaches examples writing for loops with the same variable name but in the singular form.
Example:
For number in numbers:
For course in courses:
For plane in planes:
For car in cars:
Is there a reason why most people like writing their for loops this way. For me it takes a while to understand more than if they used a different variable name entirely.
Use a dictionary instead. E.g:
doubles = dict()
for x in range(1, 13):
doubles[x] = x * 2
Or if you absolutely must do this AND ONLY IF YOU FULLY UNDERSTAND WHAT YOU ARE DOING, you can assign to locals() as to a dictionary:
>>> for x in range(1, 13):
... locals()['double_{0}'.format(x)] = x * 2
...
>>> double_3
6
There never, ever should be a reason to do this, though - since you should be using the dictionary instead!
expanding my comment: "use a dict. it is exactly why they were created"
using defaultdict:
>>> from collections import defaultdict
>>> d = defaultdict(int)
using normal dict:
>>> d = {}
the rest:
>>> for x in range(1, 13):
d['double_%02d' % x] = x * 2
>>> for key, value in sorted(d.items()):
print key, value
double_01 2
double_02 4
double_03 6
double_04 8
double_05 10
double_06 12
double_07 14
double_08 16
double_09 18
double_10 20
double_11 22
double_12 24
You probably want a dict instead of separate variables. For example
d = {}
for i in range(3):
d["group" + str(i)] = self.getGroup(selected, header+i)
If you insist on actually modifying local variables, you could use the locals function:
for i in range(3):
locals()["group"+str(i)] = self.getGroup(selected, header+i)
On the other hand, if what you actually want is to modify instance variables of the class you're in, then you can use the setattr function
for i in group(3):
setattr(self, "group"+str(i), self.getGroup(selected, header+i)
And of course, I'm assuming with all of these examples that you don't just want a list:
groups = [self.getGroup(i,header+i) for i in range(3)]
Use a list.
groups = [0]*3
for i in xrange(3):
groups[i] = self.getGroup(selected, header + i)
or more "Pythonically":
groups = [self.getGroup(selected, header + i) for i in xrange(3)]
For what it's worth, you could try to create variables the "wrong" way, i.e. by modifying the dictionary which holds their values:
l = locals()
for i in xrange(3):
l['group' + str(i)] = self.getGroup(selected, header + i)
but that's really bad form, and possibly not even guaranteed to work.
I wasn't really sure how to describe this, but bascially this is what I want to do:
a1=1;a2=2;a3=3
for i in [1,2,3]: print a(i)
I want this to print a1, a2, and a3. Is there a way to make that work?
"I want to define several variables with trailing ascending numbers 0, 1, 2, etc." is a red flag that you really should be using a list.
You probably want to defer to r/learnpython for these types of questions.
Nevertheless, it's not clear what you want to do. On the one hand, you could just make a a list and index into that:
a = [1, 2, 3]
for i in [0, 1, 2]:
print(a[i])
Or, probably what you want to do is put these things in a dictionary:
data = {'a1': 1, 'a2': 2, 'a3': 3}
for i in [1, 2, 3]:
print(data['a{}'.format(i)])
The line:
Copyvars()[rate] = 'k' + str(i)
has to be replaced by:
Copyvars()['k' + str(i)]=rate
If the items are all globals you can use the globals() call to get a mapping, then manipulate them:
Copyg = globals()
for i in arange(0,52):
varname = 'k{}'.format(i)
g[varname] = log10(g[varname])
but you really want to just store all those items in a list or dictionary instead.
You can use dictionary. This approach is better in my opinion as you can see the the key and value pair.
code
total_squares=8
box_list={}
for q in range(total_squares):
box_list['box_'+str(q)]=0
print(box_list)
output
{'box_0': 0, 'box_1': 0, 'box_2': 0, 'box_3': 0, 'box_4': 0, 'box_5': 0, 'box_6': 0, 'box_7': 0}
Creating variables dynamically is an anti-pattern and should be avoided. What you need is actually a list:
total_squares = 8
box_list = []
boxes = [0] * total_squares
for q in range(total_squares):
box_list.append(boxes[q])
Then you can refer to any element you want (say, box_i) using the following syntax:
my_box = box_list[boxes[i]]