-5

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.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Saurabh Shrivastava
  • 1,394
  • 4
  • 21
  • 50
  • 6
    Well why you need to declare 1000 variables ? – Tanveer Alam May 02 '15 at 05:43
  • Use an array or the Python equivalent... – Ismael Miguel May 02 '15 at 05:44
  • http://stackoverflow.com/questions/521674/initializing-a-list-to-a-known-number-of-elements-in-python might be of use. – bentank May 02 '15 at 05:48
  • @TanveerAlam..You can imagine a chess baord layout with each block having name as a1,a2..a8,b1.....h8. Now i dont want to write 64 different lines like a1=100,a2=100 etc. I want to do it by loop. – Saurabh Shrivastava May 02 '15 at 05:55
  • @user3388005 use a 2D list for this. Or if you have to, a dict of lists. – Adam Smith May 02 '15 at 05:56
  • 2
    This question has so many duplicates that I couldn't find which one is the canonical version, if there even is one. See [Why you don't want to dynamically create variables](http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html) for links to 11 more dups. – abarnert May 02 '15 at 06:29
  • As a side note, if you have non-trivial 2D arrays of things, you probably want to look at [NumPy](http://www.numpy.org/) or [Pandas](http://pandas.pydata.org/). – abarnert May 02 '15 at 07:11

4 Answers4

4

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")
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • 2
    Rather than sticking a `None` at the start of the list, it's a better idea to just get used to 0-indexing. `None`-padding creates awkward issues like `len` being one higher than the number of logical elements of the list. – user2357112 May 02 '15 at 06:21
  • @user2357112 agreed, which is why I implicitly converted from zero-indexing in the elegant solution. However if he's going to try and reference an element like you would a chess board, he needs to have 1-indexing. – Adam Smith May 02 '15 at 07:45
1

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.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
0

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.

IanH
  • 10,250
  • 1
  • 28
  • 32
0

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).

user2217852
  • 36
  • 2
  • 4