0
import random

a = [1,2,3,4,5,6,7,8,9]
# random.shuffle(a) # this is fine
a = random.shuffle(a) # a is now None

I made a typo in my code but I'd like to know in this case why a turns into None. What's going on under the hood?

Mr Mystery Guest
  • 1,464
  • 1
  • 18
  • 47

1 Answers1

5

random.shuffle works in-place, it does not return anything (And hence by default it returns None , since all Python function calls should return some value) , hence when you do - a = random.shuffle(a) , a becomes None. Try -

random.shuffle(a)

From documentation of random.shuffle -

random.shuffle(x[, random])

Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random().

(Emphasis mine)

Community
  • 1
  • 1
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • 2
    I know what you mean, but IMHO saying that "it does not return anything" is a little misleading, since it returns `None`. Maybe you should mention that _all_ Python functions _must_ return something, functions without an explicit `return` statement return `None`, and it's conventional for functions that mutate objects in-place to return `None`. – PM 2Ring Oct 16 '15 at 15:11
  • You are right thanks, added that as well. – Anand S Kumar Oct 16 '15 at 15:12