Pretty straight forward random password generating program.
I am generating 8 unique random numbers assigning those numbers to a variable and using that variable to print out a unique character from the alpha list.
The problem is that I am getting a "IndexError: list index out of range" error some of the times I'm running the program. I double checked and the the numbers that it's saying are out of range are totally in range since they are either 3, or 55, or etc. And I think the IndexError only pops up for the alpha list (e.g. alpha[c5]) not the actual nums list.
What am I missing? Please be gentle, I am new to programming. Sorry if this is a stupid question.
from random import random, sample
alpha = ['A','B','C','D','E','F','G','H','I','J',\
'K','L','M','N','O','P','Q','R','S','T','U','V','W',\
'X','Y','Z','a','b','c','d','e','f','g','h','i','j',\
'k','l','m','n','o','p','q','r','s','t','u','v','w',\
'x','y','z','0','1','2','3','4','5','6','7','8','9']
nums = sample(range(0,63),8)
print(nums)
c1 = nums[0]
c2 = nums[1]
c3 = nums[2]
c4 = nums[3]
c5 = nums[4]
c6 = nums[5]
c7 = nums[6]
c8 = nums[7]
print(alpha[c1],alpha[c2],alpha[c3],alpha[c4],alpha[c5],alpha[c6],\
alpha[c7],alpha[c8],end='')
That 63 should be a 62, standard one-off error. Easy fix:
nums = sample(range(0, len(alpha)), 8)
(or more concisely,nums = sample(range(len(alpha)), 8)
).You’ll achieve your result with an even more concise one-liner:
print(sample(alpha, 8))
that samples your elements directly, forgoing the need for a range.Checkout the docs of
random.sample
for more usage tips. https://docs.python.org/3/library/random.html#functions-for-integers