How do I shuffle a list of objects? I tried random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
But it outputs:
None
How do I shuffle a list of objects? I tried random.shuffle:
import random
b = [object(), object()]
print(random.shuffle(b))
But it outputs:
None
random.shuffle should work. Here's an example, where the objects are lists:
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
print(x)
# print(x) gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
Note that shuffle works in place, and returns None.
More generally in Python, mutable objects can be passed into functions, and when a function mutates those objects, the standard is to return None (rather than, say, the mutated object).
>>> import random
>>> a = ['hi','world','cat','dog']
>>> random.shuffle(a,random.random)
>>> a
['hi', 'cat', 'dog', 'world']
It works fine for me. Make sure to set the random method.
For one-liners, userandom.sample(list_to_be_shuffled, length_of_the_list) with an example:
import random
random.sample(list(range(10)), 10)
outputs: [2, 9, 7, 8, 3, 0, 4, 1, 6, 5]
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
a3 = a()
a4 = a()
b = [a1,a2,a3,a4]
random.shuffle(b)
print(b)
shuffle is in place, so do not print result, which is None, but the list.
you can either use shuffle or sample . both of which come from random module.
import random
def shuffle(arr1):
n=len(arr1)
b=random.sample(arr1,n)
return b
OR
import random
def shuffle(arr1):
random.shuffle(arr1)
return arr1
import random
class a:
foo = "bar"
a1 = a()
a2 = a()
b = [a1.foo,a2.foo]
random.shuffle(b)
In case you need an in-place shuffling and ability to manipulate seed, this snippet would help:
from random import randint
a = ['hi','world','cat','dog']
print(sorted(a, key=lambda _: randint(0, 1)))
Remember that "shuffling" is a sorting by randomised key.
You can use random.choices() to shuffle your list.
TEAMS = [A,B,C,D,E,F,G,H]
random.choices(TEAMS,k = len(TEAMS))
The above code will return a randomized list same length as your previous list.
Hope It Helps !!!