-1

I am new to Python and I am trying to create multiple variables with the values of zero.

 var1 = 0
 var2 = 0
 var3 = 0 
 so on...

How to do this in Python

  • 2
    You need a list – MSH Oct 13 '21 at 11:08
  • You probably want to store references in a list `varlist.append(0)` or a dictionary `vardict['var1']=0` so it's easy to access afterwards with `varlist[0]` or `vardict['var1']`. It's possible to make true variables `locals()['var1'] = 0`, but it's almost always a worse idea. – BatWannaBe Oct 13 '21 at 11:14
  • 1
    Does this answer your question? [How do you create different variable names while in a loop?](https://stackoverflow.com/questions/6181935/how-do-you-create-different-variable-names-while-in-a-loop) – Ptit Xav Oct 13 '21 at 11:18

4 Answers4

0

You could use a list to store your values like this:

l = []
for i in range(10):
  l.append(0)
Hugo
  • 61
  • 1
  • 4
0

It would work like this (almost what @CoolCoding123 has)

var1,var2, var3 = (0, 0, 0)
ljhoh1
  • 1
  • 2
0

You almost never need to do this, i.e. create variables dynamically. But you could do it by altering the global variable dictionary. The below would create variables var0...var9 with every one set to 0:

varnames = ['var' + str(n) for n in range(10)]
for var in varnames:
    globals()[var] = 0

However, don't do such evil things. Read up on data structures such as list and dicts.

Jussi Nurminen
  • 2,257
  • 1
  • 9
  • 16
  • Nope, nope, nope. This is about as bad as `var1, var2, var3 = (0, 0, 0)`. Sure, you may be automating the creation process, but are you going to be doing such hacks as well to fetch a name if you have to loop for all the varX? The naming scheme and the fact we're dealing with a learner means that 99.99% the answer should be `var = [0] * 3`, or `var = [0 for _ in range(3)]` if he _really_ insists about using a loop. – Reti43 Oct 13 '21 at 11:37
  • @Reti43 Well, I said it's bad. But to me, the question seems to be about creating a lot of variables in automatic fashion, so that's what I tried to answer. – Jussi Nurminen Oct 13 '21 at 11:42
  • This is a very likely case of an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Though ideally the OP should have clarified what he intends to do with them, or us to ask for that clarification. Exactly because it seems very likely they should belong to a collection instead of getting hardcoded. – Reti43 Oct 13 '21 at 11:52
0

As you asked how to create multiple variables with zero values, here is one way to do:

n = 5
data = {}
for i in range(5):
    data["var%s" % i] = 0

Later on, if you need the value of a particular index i, then you can get the value using

value = data["var%s" % index]
Vega
  • 27,856
  • 27
  • 95
  • 103
Bhaskar
  • 21
  • 5