DEV Community

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

Posted on

2 1

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)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series