-2

I'm using the random module for a program and don't want items from the list to repeat, so I'm using shuffle. The problem is when I run it, it returns None instead of the items in the list.

from random import shuffle

list = ["a", "b", "c", "d"]

new_list = []

for l in list:
   n = shuffle(list)
   new_list.append(n)
print(new_list)

2 Answers2

2

Shuffle is an in-place operation - i.e. it shuffles the original list. You can change your code to this:

from random import shuffle

list = ["a", "b", "c", "d"]

new_list = []

for i in range(0, len(list)):
   shuffle(list)
   new_list.append(list)
print(new_list)
Aziz Sonawalla
  • 2,482
  • 1
  • 5
  • 6
0

.shuffle() does the shuffle in place, @Aziz has a good answer. If you want to get return value then use .sample():

from random import sample

Alist = ["a", "b", "c", "d"]

new_list = []

for l in Alist:
   n = sample(Alist,k=len(Alist))
   new_list.append(n)
print(new_list)
Wasif
  • 14,755
  • 3
  • 14
  • 34