How to Quickly Shuffle a List in Python

Randomly organize list elements in a matter of seconds

Fatos Morina
Level Up Coding
Published in
2 min readAug 24, 2021

--

Photo by Carl Heyerdahl on Unsplash

It can be quite common that you have to work with a list:

  • You may get a list of products from an API call
  • You may get a list of people from a database
  • You may get a list of items in an online store by reading from a CSV file
  • You may get a list of numbers from a range

The list goes on.

There can be cases when you may need to randomly shuffle these elements. and Python already got your back.

There can be many paths that you can take to randomly shuffle these lists, but in this article, we are going to see 2 of them.

Let’s jump right in.

random.shuffle()

This method can be one of the most popular ones that are used.

All you have to do is import the module random and then call it with a list inside it.

It will then change the ordering of the elements in the list and place them randomly there.

Let’s take a look at it:

random.sample()

This method is similar to the previous one with a difference: It does not modify the original list. It instead returns a new sampled list.

You can also specify the number of sampled elements that you want to get as a result:

If you want to get the entire list shuffled, you simply need to mention the entire length as the second argument of the sample method:

That’s pretty much it.

There can be other methods out there as well, but let’s keep things simple with these two methods that you can start using right away in your job right now.

Thank you for taking the time to read this article all the way to the end.

I hope this helps you in some way.

--

--