How to Randomly Select from or Shuffle a List in Python



Python


In this article, we show how to randomly select from or shuffle a list in Python.


How to Randomly Select from a List

We'll now go over how to randomly select from an item in a list.

So, if you have a list of items, you can randomly select from this list by importing the random module.

Once the random module is imported into the script, then you can use the random.choice() function to select any random element of this list.

The code below randomly selects a student from the list, students.



So, this code below randomly selects an item (which represents a student) from the students list.

When I ran the code above, I got the following result.



You can see, "David" was selected.


How to Randomly Shuffle a List

We'll now show how to randomly shuffle a list.

So, if we have a list in a certain order, we can randomly shuffle it in Python using the random.shuffle() function.

The code below randomly shuffles the students list.



This will randomly shuffle the students list.

Running the code above, I got the following as my output.



So, you can see how the list has been randomly shuffled.


Related Resources

How to Generate a Random Number in Python



HTML Comment Box is loading comments...