Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shuffle the order in a list?

Tags:

python

arrays

I would like to shuffle the order of the elements in a list.

from random import shuffle
words = ['red', 'adventure', 'cat', 'cat']
shuffled = shuffle(words)
print(shuffled) # expect new order for, example ['cat', 'red', 'adventure', 'cat']

As response I get None, why?

like image 213
Hiroyuki Nuri Avatar asked Mar 08 '17 14:03

Hiroyuki Nuri


People also ask

How do you randomize the order of items in a list?

Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.

How do I shuffle the order of a list in Python?

To shuffle strings or tuples, use random. sample() , which creates a new object. random. sample() returns a list even when a string or tuple is specified to the first argument, so it is necessary to convert it to a string or tuple.

Which function is used to shuffle a list?

shuffle() function in Python. The shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list).

How can you randomize the items of a list in place in Python?

The shuffle() method randomizes the items of a list in place.


2 Answers

It's because random.shuffle shuffles in place and doesn't return anything (thus why you get None).

import random

words = ['red', 'adventure', 'cat', 'cat']
random.shuffle(words)

print(words) # Possible Output: ['cat', 'cat', 'red', 'adventure']

Edit:

Given your edit, what you need to change is:

from random import shuffle

words = ['red', 'adventure', 'cat', 'cat']
newwords = words[:] # Copy words
shuffle(newwords) # Shuffle newwords

print(newwords) # Possible Output: ['cat', 'cat', 'red', 'adventure']

or

from random import sample

words = ['red', 'adventure', 'cat', 'cat']
newwords = sample(words, len(words)) # Copy and shuffle

print(newwords) # Possible Output: ['cat', 'cat', 'red', 'adventure']
like image 135
vallentin Avatar answered Sep 20 '22 16:09

vallentin


random.shuffle() is a method that does not have a return value. So when you assign it to a identifier (a variable, like x) it returns 'none'.

like image 30
fivestarx Avatar answered Sep 22 '22 16:09

fivestarx