laptop on brown wooden table
Photo by XPS 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 is 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.

I hope this helps you in some way.