-4

I wrote some code in two different ways which I thought were exacly equivalent but I got two very differnt answers:

This first way worked exactly as expected:

test_listA = list(range(0, 5))
random.shuffle(test_listA)
print(test_listA)

It printed out:

[2, 1, 0, 3, 4]

But when I reorganised it like so:

test_listB = random.shuffle(list(range(0, 5)))
print(test_listB)

It prints out:

None

Why the difference?

Mick
  • 8,284
  • 22
  • 81
  • 173

1 Answers1

1

The problem

random.shuffle returns None and shuffles the original list in place. From the documentation:

Shuffle the sequence x in place.

Assigning the value that random.shuffle returns (None) back to the shuffled list would set the value of the variable to None.


The solution

You can copy the object and work on the copy:

import copy
import random


a = [1, 2, 3, 4]
b = copy.copy(a)
random.shuffle(b)

print(f"a = {a}")
print(f"b = {b}")

a = [1, 2, 3, 4]

b = [1, 3, 4, 2]

Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64