Get Random Element from a Python List—random.choice()
To pick a random element from a list in Python, use the random module’s choice() method:
This provides you with a quick answer. However, there are other ways you can consider. Let’s take a deeper look at randomly picking elements from lists in Python.
Random Element from a List in Python
There are six different ways to select elements randomly from a list in Python:
- random.randrange()
- random.random()
- random.choice()
- random.randint()
- random.sample()
- secrets.choice()
Let’s go through each of these methods in more detail with useful examples.
1. Random.randrange()
To choose a random value between two numbers, you can use the random.randrange() function.
To utilize this to pick a random element from a list:
- Generate a random number index between 0 and the length of the list.
- Get an element from a list based on that index.
2. Random.random()
The random.random() method returns a random floating-point number between 0 and 1.
Even though it is not that practical, you can use this method to pick a random element 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:
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 <= n < a :
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:
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:
This returns a list:
This method selects elements without replacement, i.e., it selects without duplicates and repetitions.
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!
This returns something along the lines of:
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:
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() .
Модуль random на примерах — Изучение методов генерации случайных данных

В данной статье мы рассмотрим процесс генерации случайных данных и чисел в Python. Для этого будет использован модуль random и некоторые другие доступные модули. В Python модуль random реализует генератор псевдослучайных чисел для различных распределений, включая целые и вещественные числа с плавающей запятой.
Содержание
Список методов модуля random в Python:
| Метод | Описание |
|---|---|
| seed() | Инициализация генератора случайных чисел |
| getstate() | Возвращает текущее внутренне состояние (state) генератора случайных чисел |
| setstate() | Восстанавливает внутреннее состояние (state) генератора случайных чисел |
| getrandbits() | Возвращает число, которое представляет собой случайные биты |
| randrange() | Возвращает случайное число в пределах заданного промежутка |
| randint() | Возвращает случайное число в пределах заданного промежутка |
| choice() | Возвращает случайный элемент заданной последовательности |
| choices() | Возвращает список со случайной выборкой из заданной последовательности |
| shuffle() | Берет последовательность и возвращает ее в перемешанном состоянии |
| sample() | Возвращает заданную выборку последовательности |
| random() | Возвращает случайное вещественное число в промежутке от 0 до 1 |
| uniform() | Возвращает случайное вещественное число в указанном промежутке |
| triangular() | Возвращает случайное вещественное число в промежутке между двумя заданными параметрами. Также можно использовать параметр mode для уточнения середины между указанными параметрами |
| betavariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на Бета-распределении, которое используется в статистике |
| expovariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, или же между 0 и -1 , когда параметр отрицательный. За основу берется Экспоненциальное распределение, которое используется в статистике |
| gammavariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на Гамма-распределении, которое используется в статистике |
| gauss() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на Гауссовом распределении, которое используется в теории вероятности |
| lognormvariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на Логнормальном распределении, которое используется в теории вероятности |
| normalvariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на Нормальном распределении, которое используется в теории вероятности |
| vonmisesvariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на распределении фон Мизеса, которое используется в направленной статистике |
| paretovariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на распределении Парето, которое используется в теории вероятности |
| weibullvariate() | Возвращает случайное вещественное число в промежутке между 0 и 1, основываясь на распределении Вейбулла, которое используется в статистике |
Цели данной статьи
Далее представлен список основных операций, которые будут описаны в руководстве:
- Генерация случайных чисел для различных распределений, которые включают целые и вещественные числа с плавающей запятой;
- Случайная выборка нескольких элементов последовательности population ;
- Функции модуля random;
- Перемешивание элементов последовательности. Seed в генераторе случайных данных;
- Генерация случайных строки и паролей;
- Криптографическое обеспечение безопасности генератора случайных данных при помощи использования модуля secrets. Обеспечение безопасности токенов, ключей безопасности и URL;
- Способ настройки работы генератора случайных данных;
- Использование numpy.random для генерации случайных массивов;
- Использование модуля UUID для генерации уникальных ID.
В статье также даются ссылки на некоторые другие тексты сайта, связанные с рассматриваемой темой.
Как использовать модуль random в Python
Для достижения перечисленных выше задач модуль random будет использовать разнообразные функции. Способы использования данных функций будут описаны в следующих разделах статьи.
How can I randomly select an item from a list?
How do I retrieve an item at random from the following list?
![]()
17 Answers 17
For cryptographically secure random choices (e.g., for generating a passphrase from a wordlist), use secrets.choice() :
secrets is new in Python 3.6. On older versions of Python you can use the random.SystemRandom class:
![]()
![]()
If you want to randomly select more than one item from a list, or select an item from a set, I’d recommend using random.sample instead.
If you’re only pulling a single item from a list though, choice is less clunky, as using sample would have the syntax random.sample(some_list, 1)[0] instead of random.choice(some_list) .
Unfortunately though, choice only works for a single output from sequences (such as lists or tuples). Though random.choice(tuple(some_set)) may be an option for getting a single item from a set.
EDIT: Using Secrets
As many have pointed out, if you require more secure pseudorandom samples, you should use the secrets module:
EDIT: Pythonic One-Liner
If you want a more pythonic one-liner for selecting multiple items, you can use unpacking.