random.shuffle returns None

Viewed 26

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
2 Answers

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)

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)
Related