focus photography of computer keyboard with red lights
Photo by Anas Alshanti on Unsplash

It’s inevitable that you need to work with lists in your day-to-day job. 

A list of users. A list of store items. A list of objects.

One potentially rare task that you may need to do is get a random element in a list.

There can be many ways that you can use to do that, but in this article, I am going to share 2 ways that can hopefully be helpful.


1. Using random.randint()

You have probably used methods from the random library already, trying to get a randomized numerical value that you may need to do some initializations, or adding some randomness for certain random keys. 

There is also a method that you can use to get random integers. You can set a range of integers so that we don’t just get a truly random integer in an infinite range. We need to limit it to the length of the list.

Here is the snippet:


2. Using choice()

This is a method that is prepared specifically to help us with getting a random number in a list without having to deal with the indexes.

All we have to do is import the module and then call it:

Yes, it’s that simple. No need to tinker with the indexes and having to set up the range of integers, or anything. 


That’s pretty much it.

I hope you find this helpful.