1

I'm trying to be able to add a random number generated between 1 and 5 using randint and be able to add that to a list. There are multiple lists however, so for example, on the first iteration of a loop I want it to add data to the list "car1", then on the second add the random data to the list "car2". I've attempted this below.

car1 = []
car2 = []
car3 = []
car4 = []
car5 = []

for i in range(5):
    rand0m = randint(1,5)
    car{0}.append(rand0m).format(i)

I know that the {0}.format only workds with strings, it was just to show you what Im trying to do. I am using Python 3

Coder77
  • 2,203
  • 5
  • 20
  • 28
  • I think you are better off putting your lists into a container list and iterating that container list. I understand what you are trying to do but this is not good practice whatsoever. –  Sep 25 '14 at 08:34
  • Don't use separate lists. Put the lists into another list instead. – Martijn Pieters Sep 25 '14 at 08:38

2 Answers2

1

You could store all your lists inside another list and reference the embedded lists using the index of the containing list, e.g.

car1 = []
car2 = []
car3 = []
car4 = []
car5 = []
cars = [car1,car2,car3,car4,car5]
for i in range(5):
    rand0m = randint(1,5)
    cars[i].append(rand0m)
Joko
  • 166
  • 3
  • 17
1

If you have to name variables in the manner that it is suffixed by a sequential numbers, then you ideally should create a list in python, which makes it earier to index, as you are intending here

cars = [[] for _ in range(5)]

for i in range(5):
    rand0m = randint(1,5)
    cars[i].append(rand0m)
Abhijit
  • 62,056
  • 18
  • 131
  • 204