shuffle an array in python

To shuffle an array (or list) in Python, you can use the random.shuffle() function from the built-in random module. Here's an example:

main.py
import random

my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)
80 chars
6 lines

Output:

main.py
[3, 5, 2, 1, 4]
16 chars
2 lines

The random.shuffle() function shuffles the elements of the list in place, meaning it modifies the original list. If you don't want to modify the original list, you can make a copy of it first and shuffle the copy instead:

main.py
import random

my_list = [1, 2, 3, 4, 5]
shuffled_list = my_list.copy()
random.shuffle(shuffled_list)
print(shuffled_list)
123 chars
7 lines

Output:

main.py
[2, 4, 5, 1, 3]
16 chars
2 lines

gistlibby LogSnag