Python select random from list

How to Select Random Element from a List in Python

Here are 8 ways to select random element from a list in Python:

  1. Using random.choice() method
  2. Using random.randrange() method
  3. Using random.randint() method
  4. Using random.random() method
  5. Using random.sample() method
  6. Using random.choices() method
  7. Select k random value from a list
  8. Using numpy.random.choice() method

Method 1: Using the random.choice() method

To select a random element from a list in Python, you can use the “random.choice()” method. The random choice() method returns a random element from the non-empty sequence-like list.

Example

To select a random element from the list, use the “random.choice()” method and pass the list as an argument.

import random data = ["infy", "tcs", "affle", "dixon", "astral"] print(random.choice(data))

You can see that it selects one random element from the list and returns it. If you rerun the above code, then every time, it will return a different element.

➜ python3 app.py infy ➜ python3 app.py tcs ➜ python3 app.py affle

Method 2: Using the random.randrange() method

The random.randrange() method is used to generate a random number in a given range, and we can specify the range to be 0 to the list length, get the index, and then the corresponding value.

Example

import random data = ["infy", "tcs", "affle", "dixon", "astral"] rand_idx = random.randrange(len(data)) random_num = data[rand_idx] print("Random selected element is : " + random_num)
Random selected element is : astral

Method 3: Using the random.randint() method

The random.randint() method is used to generate the random number. Also, this can be used to generate any number in a range, and then using that number, we can find the value at the corresponding index.

Читайте также:  Finding the number of days between 2 dates.

Example

import random data = [11, 19, 18, 21, 46] rand_idx = random.randint(0, len(data) - 1) random_num = data[rand_idx] print("Random selected number is : " + str(random_num))
Random selected number is : 11

Method 4: Using the random.random() method

The random.random() method is used to generate the floating-point numbers in the range of 0 to 1.

Example

import random data = [11, 19, 18, 21, 46] rand_idx = int(random.random() * len(data)) random_num = data[rand_idx] print("Random selected number is : " + str(random_num))
Random selected number is : 18

Method 5: Selecting multiple random elements from a list in Python

To select multiple random elements from a Python list, use the “random.sample()” method. The random.sample() method returns a particular length of the list chosen from a sequence.

Example

To use the sample() method in Python, import the random module in your program.

We need three random elements from the list, and then we will pass three as the second argument, which suggests the number of elements you need in the list.

import random data = ["infy", "tcs", "affle", "dixon", "astral"] print(random.sample(data, 3))

Method 6: Using the random.choices() method

The random.choices() method is “used to select numerous elements from a list or a single element from a specific sequence.”

Example

import random data = [11, 19, 18, 21, 46] print("Random selected number is : ", random.choices(data, k = 3))
Random selected number is : [46, 46, 21]

Method 7: Select k random value from a list

import random def select_random_Ns(l, k): random.shuffle(l) result = [] for i in range(0, len(l), k): result.append(l[i:i + k]) return result lst = ['D', 'A', 'T', 'A', 'B', 'A', 'S', 'E'] print(select_random_Ns(lst, 4)) 

Method 8: Using the numpy.random.choice() method

import numpy as np data = [21, 19, 18, 46] arr = np.array(data) random_num = np.random.choice(arr) print("Random selected number is : " + str(random_num)) 
Random selected number is : 18

Источник

How to Randomly Select Elements from a List in Python

Selecting a random element or value from a list is a common task — be it for randomized results from a list of recommendations or just a random prompt.

In this article, we’ll take a look at how to randomly select elements from a list in Python. We’ll cover the retrieval of both singular random elements, as well as retrieving multiple elements — with and without repetition.

Читайте также:  Php как убрать экранирование кавычек

Selecting a Random Element from Python List

The most intuitive and natural approach to solve this problem is to generate a random number that acts as an index to access an element from the list.

To implement this approach, let’s look at some methods to generate random numbers in Python: random.randint() and random.randrange() . We can additionally use random.choice() and supply an iterable — which results in a random element from that iterable being returned back.

Using random.randint()

random.randint(a, b) returns a random integer between a and b inclusive.

We’ll want random index in the range of 0 to len(list)-1 , to get a random index of an element in the list:

import random letters = ['a', 'b', 'c', 'd', 'e', 'f'] random_index = random.randint(0,len(letters)-1) print(letters[random_index]) 

Running this code multiple times yields us:

Using random.randrange()

random.randrange(a) is another method which returns a random number n such that 0

import random letters = ['a', 'b', 'c', 'd', 'e', 'f'] random_index = random.randrange(len(letters)) print(letters[random_index]) 

Running this code multiple times will produce something along the lines of:

As random.randrange(len(letters)) returns a randomly generated number in the range 0 to len(letters) — 1 , we use it to access an element at random in letters , just like we did in the previous approach.

This approach is a tiny bit simpler than the last, simply because we don’t specify the starting point, which defaults to 0 .

Using random.choice()

Now, an even better solution than the last would be to use random.choice() as this is precisely the function designed to solve this problem:

import random letters = ['a', 'b', 'c', 'd', 'e', 'f'] print(random.choice(letters)) 

Running this multiple times results in:

Selecting More than One Random Element from Python List

Using random.sample()

The first method that we can make use of to select more than one element at random is random.sample() . It produces a sample, based on how many samples we’d like to observe:

import random letters = ['a', 'b', 'c', 'd', 'e', 'f'] print(random.sample(letters, 3)) 

This method selects elements without replacement, i.e., it selects without duplicates and repetitions.

print(random.sample(letters, len(letters))) 

Since it doesn’t return duplicates, it’ll just return our entire list in a randomized order:

Читайте также:  Java 64 bit jar

Using random.choices()

Similar to the previous function, random.choices() returns a list of randomly selected elements from a given iterable. Though, it doesn’t keep track of the selected elements, so you can get duplicate elements as well:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

import random letters = ['a', 'b', 'c', 'd', 'e', 'f'] print(random.choices(letters, k=3)) 

This returns something along the lines of:

print(random.choices(letters, k = len(letters))) 

It can return something like:

random.choices returns a k -sized list of elements selected at random with replacement.

This method can also be used implement weighted random choices which you can explore further in the official Python documentation.

Selecting Random n Elements with No Repetition

If you’re looking to create random collections of n elements, with no repetitions, the task is seemingly more complex than the previous tasks, but in practice — it’s pretty simple.

You shuffle() the list and partition it into n parts. This ensures that no duplicate elements are added, since you’re just slicing the list, and we’ve shuffled it so the collections are random.

If you’d like to read more about splitting a list into random chunks take a look at — How to Split a List Into Even Chunks in Python.

We’ll save the result in a new list, and if there’s not enough elements to fit a final collection, it’ll simply be unfinished:

import random def select_random_Ns(lst, n): random.shuffle(lst) result = [] for i in range(0, len(lst), n): result.append(lst[i:i + n]) return result lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(select_random_Ns(lst, 2)) 

This results in a list of random pairs, without repetition:

Conclusion

In this article, we’ve explored several ways to retrieve one or multiple randomly selected elements from a List in Python.

We’ve accessed the list in random indices using randint() and randrange() , but also got random elements using choice() and sample() .

Источник

Оцените статью