Ron Jensen
0
Q:

randomly shuffle array python

import random
number_list = [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]
print ("Original list : ",  number_list)

random.shuffle(number_list) #shuffle method
print ("List after shuffle  : ",  number_list)
13
# Basic syntax:
import random
random.shuffle(your_list)

# Example usage:
your_list = ['list', 'of', 'amazing', 'words', 'and', 'numbers', 1, 2, 3]
random.shuffle(your_list)
print(your_list)
--> [2, 'list', 'words', 1, 3, 'numbers', 'of', 'amazing', 'and']

# Note, random.shuffle shuffles your list in place
# Note, if you want to shuffle in the same way each time, you can set
#	a seed with random.Random(seed).shuffle() as follows:
your_list = ['list', 'of', 'amazing', 'words', 'and', 'numbers', 1, 2, 3]
random.Random(0).shuffle(your_list)
print(your_list)
--> [2, 'numbers', 'of', 'words', 'and', 'amazing', 'list', 3, 1]

your_list = ['list', 'of', 'amazing', 'words', 'and', 'numbers', 1, 2, 3]
random.Random(0).shuffle(your_list)
print(your_list)
--> [2, 'numbers', 'of', 'words', 'and', 'amazing', 'list', 3, 1]
# Note, your_list was shuffled in the same way each time, which wouldn't
#	have been true without the use of random.Random(seed)
3
import random
l = list(range(5))
print(l)
# [0, 1, 2, 3, 4]

lr = random.sample(l, len(l))
print(lr)
# [3, 2, 4, 1, 0]

print(l)
# [0, 1, 2, 3, 4]
2

New to Communities?

Join the community