JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

How to Randomly Select Elements from a List in Python

Author:JIYIK Last Updated:2025/05/05 Views:

This tutorial showed you how to randomly select an element from a list in Python. There are multiple simple ways to achieve this goal, all of which involve importing Python modules.

This tutorial will cover solutions that require the random, , secretsand modules.NumPy

Please note that all of these solutions that will be presented will use a pseudo-random number generator (PRNG).


randomSelect a random element from a list in Python using the module

The most commonly used randomization module is randomthe module. This module implements pseudo-random utility functions to support operations involving randomization.

Let's say we want to randomly pick a name from a list, like voting.

["John", "Juan", "Jane", "Jack", "Jill", "Jean"]

To pick a random name from this list, we will use random.choice()which will select an element from the available data given.

import random

names = ["John", "Juan", "Jane", "Jack", "Jill", "Jean"]


def selectRandom(names):
    return random.choice(names)


print("The name selected is: ", selectRandom(names))

Of course, the output will be variable and random, so it could be namesany of the six names stored in the variable .


secretsSelect a random element from a list using the module in Python

secretsThe module serves essentially randomthe same purpose as . However, secretsa cryptographically secure method of implementing a PRNG is provided.

In real life applications, such as storing passwords, authentication, encryption and decryption, and tokens. It is much safer secretsthan using random, as it is only suitable for operations that simulate or do not handle sensitive data.

In this problem, the values ​​provided by both modules are the same because we are not handling any sensitive data and this is for simulation purposes.

In this example, we will use the same nameslist. secretsThere is also a version of the function choice()that produces the random.choice()same variable output as .

import secrets

names = ["John", "Juan", "Jane", "Jack", "Jill", "Jean"]


def selectRandom(names):
    return secrets.choice(names)


print("The name selected is: ", selectRandom(names))

NumPySelect a random element from a list in Python using the module

NumPyThe module also has utility functions for randomization, and some extensibility tools as choice()arguments to its functions.

Again, we will use the same list namesto demonstrate the function numpy.random.choice().

import numpy

names = ["John", "Juan", "Jane", "Jack", "Jill", "Jean"]


def selectRandom(names):
    return numpy.random.choice(names)


print("The name selected is: ", selectRandom(names))

This function will return the same variable output as produced by the other two modules.

NumPyAdditional arguments are provided choice()to generate multiple outputs in the form of a list.

The second parameter accepts an integer value that determines how many random items to return. Suppose we want namesto return 4 random elements from the list.

def selectRandom(names):
    return numpy.random.choice(names, 4)


print("The names selected are: ", selectRandom(names))

Sample output:

The names selected are: ['John', 'Jill', 'Jill', 'Jill']

In the random results, it is possible for the same element to be repeated more than once.

If you want the resulting items to be unique, we can pass a third booleanparameter to perform random sampling without replacement.

def selectRandom(names):
    return numpy.random.choice(names, 4, False)

Output example:

The names selected are: ['Jill', 'John', 'Jack', 'Jean']

This function will always produce a unique list without any repeated elements.

If we add a third argument, one major drawback is the running time of the function, since it will perform an extra task to check for duplicate elements and replace them with elements that are not yet present in the result.

To summarize, selecting random items from a Python list can be achieved by using one of these three modules: random, , secretsor NumPy. Each module has its advantages and disadvantages.

If you want to have a cryptographically secure PRNG approach, then secretsis the best module. If your purpose is just for simulation or non-sensitive data manipulation, then use randomor NumPy. If you want more than one random result in the result, then use NumPy.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Read the first line of a file in Python

Publish Date:2025/05/05 Views:192 Category:Python

In Python, we have built-in functions to handle different file operations. A text file contains a sequence of strings where each line \n is terminated by a newline character. In this tutorial, we will learn how to read the first line of a t

How to Replace an Element in a Python List

Publish Date:2025/05/05 Views:109 Category:Python

We can replace elements in Python lists in many ways. We can use Python list element indexing, for loops, map functions, and list comprehensions. This article will discuss the above methods to find and replace elements in Python lists. Sear

Convert Tensor to NumPy array in Python

Publish Date:2025/05/03 Views:86 Category:Python

This tutorial will show you how to convert a Tensor to a NumPy array in Python. Use the function in Python Tensor.numpy() to convert a tensor to a NumPy array Eager Execution of TensorFlow library can be used to convert tensor to NumPy arra

Saving NumPy arrays as images in Python

Publish Date:2025/05/03 Views:194 Category:Python

In Python, numpy module is used to manipulate arrays. There are many modules available in Python that allow us to read and store images. An image can be thought of as an array of different pixels stored at specific locations with correspond

Transposing a 1D array in NumPy

Publish Date:2025/05/03 Views:98 Category:Python

Arrays and matrices form the core of this Python library. The transpose of these arrays and matrices plays a vital role in certain topics such as machine learning. In NumPy, it is easy to calculate the transpose of an array or a matrix. Tra

Find the first index of an element in a NumPy array

Publish Date:2025/05/03 Views:59 Category:Python

In this tutorial, we will discuss how to find the first index of an element in a numpy array. Use where() the function to find the first index of an element in a NumPy array The function in the numpy module where() is used to return an arra

Remove Nan values from NumPy array

Publish Date:2025/05/03 Views:119 Category:Python

This article discusses some built-in NumPy functions that you can use to remove nan values. Remove Nan values ​​using logical_not() and methods in NumPy isnan() logical_not() is used to apply logical NOT to the elements of an array. isn

Normalizing a vector in Python

Publish Date:2025/05/03 Views:51 Category:Python

A common concept in the field of machine learning is to normalize a vector or dataset before passing it to the algorithm. When we talk about normalizing a vector, we say that its vector magnitude is 1, being a unit vector. In this tutorial,

Calculating Euclidean distance in Python

Publish Date:2025/05/03 Views:128 Category:Python

In the world of mathematics, the shortest distance between two points in any dimension is called the Euclidean distance. It is the square root of the sum of the squares of the differences between the two points. In Python, the numpy, scipy

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial