Inplace shuffle function returns none

Steve D'Aprano steve+python at pearwood.info
Tue Oct 18 20:44:33 EDT 2016


On Wed, 19 Oct 2016 07:25 am, Sayth Renshaw wrote:

> So why can't i assign the result slice to a variable b?
> 
> It just keeps getting none.

Of course you can assign the result slice to b. You just have to do it the
right way. 

You keep getting None because you do it the wrong way. Unfortunately you
aren't showing us your code, so we have no idea what you are doing wrong.
My guess is that you are doing something like this:


a = [1, 2, 3, 4, 5, 6, 7, 8]
b = random.shuffle(a)[0:3]

That's wrong -- shuffle() modifies the list you pass, and returns None. You
cannot take a slice of None. Try this:

a = [1, 2, 3, 4, 5, 6, 7, 8]
random.shuffle(a)
b = a[0:3]
print(b)




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list