I have 1000 variables, a1,a2,a3,a4,a5
and so on. Is there a way to initialize all to value 100 using loop
My attempt:
for i in range(1,1001):
"a"i=100
I am missing basic syntax here.
I have 1000 variables, a1,a2,a3,a4,a5
and so on. Is there a way to initialize all to value 100 using loop
My attempt:
for i in range(1,1001):
"a"i=100
I am missing basic syntax here.
Don't ever ever do this. You gain absolutely nothing from doing it this way. How can you possibly REFER to these variables dynamically if you're setting them this way? Use a list or a dictionary instead.
a_list = [None] + [100] * 1000
# `a_list[n]` in place of `an`, here
a_dict = {num:100 for num in range(1, 1001)}
# `a_dict[n]` in place of `an`, here
edit for your chess board analogy:
import string
class ChessBoard(list):
def __init__(self, side_length, initial_value=None):
super().__init__()
for _ in range(side_length):
self.append([initial_value for _ in range(side_length)])
def get(self, notation):
"""Maps chess notation to the 2D list"""
indices = dict([(lett, num) for num,lett in
enumerate(string.ascii_letters, start=1)])
# {'a':1, 'b':2, ... 'Z':52}
x, y = indices[notation[0]]-1, int(notation[1])-1
return self[y][x]
board = ChessBoard(1000, 100) # how do we index the 1000th...nevermind
board.get("a6")
I'll reiterate that this is a bad practice but you could do this.
for i in xrange(1, 1001):
globals()['a%s' % i] = 100
for i in xrange(1, 1001):
name = 'a%d' % i
print '%s = %d' % (name, globals()[name])
The second loop just prints them.
To do something like this you really ought to use a list. Initializing a length 1000 list with each entry set to 100 can be done by
a = [100] * 1000
You can set variables like this outside a list using exec
, but that is not good practice unless you have some strange compelling reason to do so.
Note that the entries will be indexed from 0 to 999.
You can do this using Python Arrays/Lists. For your case you could create a list of 1000 100s by doing the following:
my_array = [100]*1001
To find a certain value in that list you "index" into it. For example:
print(my_array[300])
The print statement would print the 301st value in the list (as array indexes start counting at 0).