简体   繁体   中英

How to shuffle the order in a list?

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?

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']

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'.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM