Shuffling a list without changing the original list

Question:

Say that I have a list with elements:

listA = [1, 2, 3, 4, 5]

print(listA) returns:

[1, 2, 3, 4, 5]

I want to randomize the elements in listA, but then store this information in listB

import random
listB = random.shuffle(listA)

but if I print listB, it returns None

print(listB)
None

Instead, if I print listA, it returns the randomized list

print(listA)
[3, 2, 1, 4, 5]

What is going on here? How to I re-declare a variable with a new name after applying a function?

Asked By: user15141497

||

Answers:

You can use random.sample function.

import random

listA = [1, 2, 3, 4, 5] 
listB = random.sample(listA, len(listA))
Answered By: zerg468
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.