Inplace shuffle function returns none

Peter Otten __peter__ at web.de
Wed Oct 19 04:00:28 EDT 2016


Steve D'Aprano wrote:

> 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)

But once you understand how it works consider

>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
>>> random.sample(a, 3)
[1, 5, 2]

instead. This should be more efficient for "small" samples and leaves `a` 
intact:

>>> a
[1, 2, 3, 4, 5, 6, 7, 8]





More information about the Python-list mailing list