0

I want to make a program that generates a certain number of random lists and then places these into another list. This is my code:

import random

RandomPassword=["0","0","0"]
PasswordList=[]
for Char in range(0,3):
    RandomPassword[Char]=(random.randint(0,9))
    PasswordList.append(RandomPassword)
print("Password list is", PasswordList)

I have used the .append() function to try and do this, but every time I run the program I end up with something like this:

Password list is [[4, 8, 1], [4, 8, 1], [4, 8, 1]]
>>> 

I think it is something to do with the list being a mutable data type, but I'm not sure how to change this. I have trawled the internet and not found anything that I can understand that fixes my problem. I would like to see something like this:

Password list is [[3, 6, 7], [4, 8, 6], [2, 5, 4]]
>>>

Does anyone have a simple solution?

Pizza252
  • 3
  • 2
  • What output are you expecting? – khelwood Mar 27 '21 at 12:51
  • Add `random.seed()` before the line `for ....`, will give different results between runs, see: https://stackoverflow.com/questions/22639587/random-seed-what-does-it-do – Luuk Mar 27 '21 at 12:53
  • If the object is to return 1 list with 3 numbers, you should change the indentation of the line `PasswordList.append(RandomPassword)` – Luuk Mar 27 '21 at 13:03
  • @khelwood I have changed the post so that it shows the outcome I want. Hope this makes it easier to understand! – Pizza252 Mar 27 '21 at 13:07

1 Answers1

0

You must create a new list inside your loop, like so:

import random

PasswordList=[]
for Char in range(0,3):
    RandomPassword=["0","0","0"]
    RandomPassword[Char]=(random.randint(0,9))
    PasswordList.append(RandomPassword)
print("Password list is", PasswordList)

Otherwise, you add and modify the same list object three times.

  • Thank you! The actual answer involved repeating 'RandomPassword[0]', 'RandomPassword[1]' and so on - a bit clumsy but that was all I needed! Thank you taking the time to help me – Pizza252 Mar 27 '21 at 13:50