-1

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
user15141497
  • 73
  • 1
  • 6
  • 2
    `random.shuffle` modifies the list in-place. This is [*clearly documented*](https://docs.python.org/3/library/random.html#random.shuffle) – juanpa.arrivillaga Oct 06 '22 at 20:23

1 Answers1

3

You can use random.sample function.

import random

listA = [1, 2, 3, 4, 5] 
listB = random.sample(listA, len(listA))
zerg468
  • 104
  • 3
  • 1
    As already shown [here](https://stackoverflow.com/a/17649901) and [here](https://stackoverflow.com/a/27882193). – mkrieger1 Oct 06 '22 at 20:27