- How to Randomly Select Elements from a List in Python
- Selecting a Random Element from Python List
- Using random.randint()
- Using random.randrange()
- Using random.choice()
- Selecting More than One Random Element from Python List
- Using random.sample()
- Using random.choices()
- Free eBook: Git Essentials
- Selecting Random n Elements with No Repetition
- Conclusion
- Generate a List of Random Integers in Python
- 1. randint() to Generate List of Integers
- Example-
- 2. randrange() to Generate List of Numbers
- Example-
- 3. sample() to Generate List of Integers
- Example-
- Generating random number list in Python
- Generating a Single Random Number
- Example
- Output
- Generating Number in a Range
- Example
- Output
- Generating a List of numbers Using For Loop
- Example
- Output
- Using random.sample()
- Example
- Output
- Generate Random Numbers using Python
- Introduction
- Generate random numbers
- List of random numbers
- Choosing random items from a list
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.
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:
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() .
Generate a List of Random Integers in Python
This tutorial explains several ways to generate random numbers list in Python. Here, we’ll mainly use three Python random number generation functions. These are random.randint(), random.randrange(), and random.sample().
You can find full details of these methods here: Python random number generator . All these functions are part of the Random module. It employs a fast pseudorandom number generator which uses the Mersenne Twister algorithm.
However today, we’ll focus on producing a list of non-repeating integers only. Go through the below bullets to continue.
Generating a random number is crucial for some applications and possessing many usages. Let’s try to understand each of these functions with the help of simple examples.
1. randint() to Generate List of Integers
It is a built-in method of the random module. Read about it below.
It returns a random integer value in the given range.
Error status:
Example-
""" Desc: Generate a list of 10 random integers using randint() """ import random Start = 9 Stop = 99 limit = 10 RandomListOfIntegers = [random.randint(Start, Stop) for iter in range(limit)] print(RandomListOfIntegers)
[35, 86, 97, 65, 86, 53, 94, 15, 64, 74]
2. randrange() to Generate List of Numbers
It produces random numbers from a given range. Besides, it lets us specify the steps.
Return value:
It returns a sequence of numbers beginning from start to stop while hopping the step value.
Error status:
It throws a ValueError when the stop value is smaller or equals to the start, or the input number is a non-integer.
Read more about, here Python randrange().
Example-
""" Desc: Generate a list of 10 random integers using randrange() """ import random Start = 9 Stop = 99 limit = 10 # List of random integers without Step parameter RandomI_ListOfIntegers = [random.randrange(Start, Stop) for iter in range(limit)] print(RandomI_ListOfIntegers) Step = 2 # List of random integers with Step parameter RandomII_ListOfIntegers = [random.randrange(Start, Stop, Step) for iter in range(limit)] print(RandomII_ListOfIntegers)
[52, 65, 26, 58, 84, 33, 37, 38, 85, 82] [59, 29, 85, 29, 41, 85, 55, 59, 31, 57]
3. sample() to Generate List of Integers
It is a built-in function of Python’s random module. It returns a list of items of a given length which it randomly selects from a sequence such as a List, String, Set, or a Tuple. Its purpose is random sampling with non-replacement.
- seq: It could be a List, String, Set, or a Tuple.
- k: It is an integer value that represents the size of a sample.
Return value:
It returns a subsequence of k no. of items randomly picked from the main list.
Example-
""" Desc: Generate a list of 10 random integers using sample() """ import random Start = 9 Stop = 99 limit = 10 # List of random integers chosen from a range Random_ListOfIntegers = random.sample(range(Start, Stop), limit) print(Random_ListOfIntegers)
[97, 64, 82, 85, 96, 93, 76, 62, 36, 34]
We hope that after wrapping up this tutorial, you should feel comfortable to generate random numbers list in Python. However, you may practice more with examples to gain confidence.
Also, to learn Python from scratch to depth, do read our step by step Python tutorial .
Generating random number list in Python
There is a need to generate random numbers when studying a model or behavior of a program for different range of values. Python can generate such random numbers by using the random module. In the below examples we will first see how to generate a single random number and then extend it to generate a list of random numbers.
Generating a Single Random Number
The random() method in random module generates a float number between 0 and 1.
Example
import random n = random.random() print(n)
Output
Running the above code gives us the following result −
Generating Number in a Range
The randint() method generates a integer between a given range of numbers.
Example
import random n = random.randint(0,22) print(n)
Output
Running the above code gives us the following result −
Generating a List of numbers Using For Loop
We can use the above randint() method along with a for loop to generate a list of numbers. We first create an empty list and then append the random numbers generated to the empty list one by one.
Example
import random randomlist = [] for i in range(0,5): n = random.randint(1,30) randomlist.append(n) print(randomlist)
Output
Running the above code gives us the following result −
Using random.sample()
We can also use the sample() method available in random module to directly generate a list of random numbers.Here we specify a range and give how many random numbers we need to generate.
Example
import random #Generate 5 random numbers between 10 and 30 randomlist = random.sample(range(10, 30), 5) print(randomlist)
Output
Running the above code gives us the following result −
Generate Random Numbers using Python
In this article, I will explain the usage of the random module in Python. As the name implies it allows you to generate random numbers.
This random module contains pseudo-random number generators for various distributions.
The function random() is one of them, it generates a number between 0 and 1.
But there are other like the functions randint(min,max) and randrange(max) .
Introduction
Lets start with the absolute basic random number generation. The function random.random() .
The function random() returns the next random float in the range [0.0, 1.0].
import random
x = random.random()
print(x)
This outputs any number between 0 and 1. For most apps, you will need random integers instead of numbers between 0 and 1.
Generate random numbers
The function randint() generates random integers for you. If you call the function, it returns a random integer N such that a
The randint() method to generates a whole number (integer). You can use randint(0,50) to generate a random number between 0 and 50.
import random
x = random.randint(0,50)
print(x)
To generate random integers between 0 and 9, you can use the function randrange(min,max) .
from random import randrange
print(randrange(10))
You can use randint(min,max) instead:
import random
print(random.randint(0,9))
Change the parameters of randint() to generate a number between 1 and 10.
import random
x = random.randint(1,10)
print(x)
List of random numbers
import random
mylist = []
for i in range(0,100):
x = random.randint(1,10)
mylist.append(x)
print(mylist)
But this can be done in a much more compact way in Python, with a one liner.
The function to use is sample() which shuffles the input list, in the example below it shuffles the created list range(1,101) .
That is to say, range(1,101) creates a list of numbers 1 to 100.
>>> list(range(1,101)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
Then the function sample() shuffles that list in random order.
>>> import random
>>> x = random.sample(range(1,101), 100)
Choosing random items from a list
You can use the sample() method to put the list in a random order. But you can also use it get random items from a list.
import random
mylist = [1,2,3,4,5,6,7,8,9,10]
x = random.sample(mylist,3)
print(x)
If you want to pick a random item, you can use the choice(list) method. But this returns only one element.
>>> import random
>>> x = list(range(1,101))
>>> random.choice(x)
8
>>> random.choice(x)
11
>>>
You can use the method shuffle(list) to shuffle the list order and then use the first index as random number.
>>> import random
>>> x = list(range(1,101))
>>> random.shuffle(x)
The recommended way to do this is using the choice() method, but all of these work.