-1

I am doing a python project in which I want to create several variables that all hold the same information; however, I cannot figure this out on my own.

Instead of writing:

a = 1
b = 1
c = 1

and so on, I want to automate this process. Here are some examples of what I have tried so far:

Example 1:

random.randint(0, 100) = 1

Example 2:

str(random.randint(0, 100)) = 1

Example 3:

class makevariable:
  random = 0

setattr(makevariable, 'random', random.randint(0, 1000)) 
getattr(makevariable, 'random') = 1
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • I think what you want is a list, rather than a bunch of individually named variables. For example, to have a list of 10 1's, you could write `foo = [1] * 10`, or `foo = [1 for _ in range(10)]`. – Samwise May 31 '21 at 22:24
  • … Probably more like `foo = [randint(0, 1000) for _ in range(10)]`. – martineau May 31 '21 at 22:54

1 Answers1

0

You probably want a list (possibly a dictionary, dict).

import random

my_vars = [random.randint(0, 100), random.randint(0, 100), random.randint(0, 100)] # a list
print(my_vars)

# alternatively..
my_vars = [] # an empty list
for ix in range(3):
    my_vars.append(random.randint(0, 100)) # add one element at a time
print(my_vars)

# ... or more smoothly constructed using comprehension
my_vars = [random.randint(0, 100) for ix in range(3)]
print(my_vars)

# look at just the first element
print(my_vars[0]) # note the list is zero indexed

# look at just the second element
print(my_vars[1])

# how many elements?
print( len(my_vars) )

# doesn't have to be the same type
my_vars = ['fred', 3, 100/7, "Hello"]

# iterate across the list
for one_var in my_vars:
    print(one_var)

etc. - review the Python documentation and tutorials.

Joffan
  • 1,485
  • 1
  • 13
  • 18
  • The indicated duplicate question gives lots of good information about dictionaries. I suspect from your example that it's likely you would find a list to be more useful. – Joffan May 31 '21 at 22:44