DEV Community

Cover image for Shuffling and Sorting in Python
Daniel Nogueira
Daniel Nogueira

Posted on

Shuffling and Sorting in Python

Shuffling can be an interesting function in a program, even more if we want to ensure more randomness in a set of data that will be chosen.

We'll import the random library and create a list of integers to use in our example.

import random
list = [10,20,30,40,50]
Enter fullscreen mode Exit fullscreen mode

And finally, to shuffle the list, we'll use the shuffle method. If we print the list, we can see the shuffled elements.

random.shuffle(list)
print(list)
Enter fullscreen mode Exit fullscreen mode

Result example:

[50, 40, 20, 10, 30]
Enter fullscreen mode Exit fullscreen mode

And to make a random choice, we use the choice method.

x = random.choice(list)
print(x)
Enter fullscreen mode Exit fullscreen mode

Result example:

30
Enter fullscreen mode Exit fullscreen mode

Top comments (0)