-4

I am making a program that has a for loop and every time the loop is ran I want it to make a new variable like

for item in range(0, size)
     (Make new variable bit1, bit2, bit3, bit4, etc with value of 0)

Is this possible?

  • The easiest is with `globals()["bit" + str(i+1)] = 0`. But most likely it is a bad idea, and you should use a dictionary. – onodip Nov 11 '19 at 23:50

2 Answers2

0

Create a List of variables and append to it like this:

bits = []
for item in range(0, size)
    bits.append(0)

# now you have bits[0], bits[1], bits[2], etc, all set to 0
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

We can do this by appending to the vars() dictionary in the program.

for index, item in enumerate(range(size)):
     vars()[f'bit{index+1}'] = 0

Try calling the names now:

>>> bit1
0

And while this works, I'd recommend using a list or a dict instead.

Ben Soyka
  • 816
  • 10
  • 25