1

random.shuffle() returns None, can i get a shuffled value instead?

import random

testlist1 = ["1", "2"]
testlist2 = ["1a", "1b"]
testlist3 = ["2a", "2b"]

def generator(testlist1, testlist2, testlist3):
    genwords = ([random.choice(testlist1), random.choice(testlist2), random.choice(testlist3)])
    shufflegen = random.shuffle(genwords)
    print(shufflegen)

generator(testlist1, testlist2, testlist3)

Debug:

None
Galuxosi
  • 13
  • 3
  • Maybe you want [`random.choice()`](https://docs.python.org/3/library/random.html#random.choice) – 001 Sep 23 '22 at 18:06
  • I'd avoid naming your function simply `generator` as that word has a special meaning in Python https://docs.python.org/3/glossary.html#term-generator – ti7 Sep 23 '22 at 18:10

2 Answers2

2

random.shuffle doesn't return a new list. It shuffle the list you passed in place.

genwords is shuffled in your case. Print genwords. (And you may want to copy it before shuffling, if you needed it unshuffled)

import random

testlist1 = ["1", "2"]
testlist2 = ["1a", "1b"]
testlist3 = ["2a", "2b"]

def generator(testlist1, testlist2, testlist3):
    genwords = ([random.choice(testlist1), random.choice(testlist2), random.choice(testlist3)])
    random.shuffle(genwords)
    print(genwords)

generator(testlist1, testlist2, testlist3)
chrslg
  • 9,023
  • 5
  • 17
  • 31
0

random.shuffle performs inplace shuffling. Your code becomes:

import random

testlist1 = ["1", "2"]
testlist2 = ["1a", "1b"]
testlist3 = ["2a", "2b"]

def generator(testlist1, testlist2, testlist3):
    genwords = ([random.choice(testlist1), random.choice(testlist2), random.choice(testlist3)])
    random.shuffle(genwords)
    print(genwords)

generator(testlist1, testlist2, testlist3)
sarashs
  • 1
  • 1