-1

I am trying to make a list with the numbers 1-24 all in it in a random order, why doesn't this work?

full_list = []

x = 0
while x < 25 :
    n = randint (1,24) 
    while n in full_list:
        n = randint (1,24)
    full_list.append(n)
    x = x + 1
Jmango
  • 3
  • 2

1 Answers1

7

random has a shuffle function that would make more sense for this task:

ar = list(range(1,25))
random.shuffle(ar)
ar
> [20, 14, 2, 11, 15, 10, 3, 4, 16, 23, 13, 19, 5, 21, 8, 7, 17, 9, 6, 12, 22, 18, 1, 24]

Also, your solution doesn't work because while x < 25 needs to be while x < 24. It is in an infinite loop when x = 24 (since randint(1,24) will never generate a new number not in the list).

anthonybell
  • 5,790
  • 7
  • 42
  • 60