How to randomize list in python

How to randomize list in python

6 Popular Ways to Randomly Select from List in Python

Here we will learn about how to randomly select from the list in python. We will learn some of the popular ways. Some of the methods are familiar to us but some of them are new to us. We can get random elements using a random module. In this article, we will learn How to select a single random and multiple random elements. With that, we also learn how to select random elements without repetition.

Select a random element from a list

There are many methods available to get a random element from a list. First, we will learn how to get a single random element from a list. For that, we are using some methods like random.choice(), random.randint(), random.randrange(), and secret module. These are the ways to get only one random element from a list.

1. Using random.choice() Method to Randomly Select from list in Python

This method returns a random element from a list, set, or tuple.

Syntax

Parameter

sequence: A sequence may be a list, tuple, or set.

Returns

Get a random element from list using random.choice()

Import a random module. Now create a list with elements and integers. Next using random.choice() to get a random element from the list.

Output

2. Using random.randint() Method Randomly Select from list in Python

random.randint() is one of the methods in a random module. It is useful to get a random element from the specified range.

Syntax

Parameters

Returns

Get a random element from list using random.randint()

Import a random module. Now create a list with elements and integers. Next using random.randint() to get a random element from the list.

Output

3. Using random.randrange() Method to Randomly Select from list in Python

random.randrange() is one of the methods in a random module. It is useful to get a random element from the specified range. If the start value is not specified it will take the value from 0.

Syntax

Parameters

Returns

Get a random element from a list using random.randrange()

Import a random module. Now create a list with elements and integers. Next using random.randrange() to get a random element from the list.

Output

4. Using Secret Module Randomly Select from list in Python

A secret is a module that is in-built in python. It is useful to get a random number in python.

Syntax

Parameter

sequence: list, set, or tuple

Returns

Get a random element from a list using secret module

Import a secret module. Now create a list with elements and integers. Next using secret.choice() to get a random element from the list.

Output

Select multiple random elements from a list

Till we saw how to get a single random element. Now we will move on to the multiple random elements. To get multiple random elements we are using random.sample(), and random.choices(). These are the methods to get more than one random element.

5. By random.sample() method

random.sample() is a built-in function in python.random module holds the function random.sample(). It is useful to select multiple elements from a list.

Syntax

Parameters

Returns

multiple random elements

Get random elements from a list using random.sample

Import a random module. Now create a list with elements and integers. Next using a random.sample() to get random elements from the list.

Output

6. Using random.choices() Method to Randomly Select from list in Python

random.choices() is a built-in function in python. The random module holds the function random.choices(). It is useful to select multiple elements from a list or a single element from a given sequence.

Syntax

Parameters

Returns

random multiple elements

Get random elements from a list using random.choices

Import a random module. Now create a list with elements and integers. Next using random.choices() to get random elements from the list.

Output

Difference Between random.choice() and random.choices()

random.choice()random.choices()
This is useful to generate a single random element from a given sequenceThis is useful to generate a single as well as multiple random elements from a given sequence
It only takes one positional argument.It takes more than one positional argument
The output will be in a normal formThe output will be in a given sequence

Bonus: How to get random elements without repetition

Output

FAQs Related to Randomly Select From List in Python

The output will be in the form of a list. Because the input given is a list.

No, we don’t get multiple random elements using random.choice().

Final Thoughts

Here we came to the end of the article. In this article, we learned about how to get random elements in a list. We hope this article was interesting and easy to learn. random is a module that is useful to get random elements.

Try to solve all the programs on your own. If there are any methods available mention them in the comments.

random — Generate pseudo-random numbers¶

Source code: Lib/random.py

This module implements pseudo-random number generators for various distributions.

For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.

On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state.

The random module also provides the SystemRandom class which uses the system function os.urandom() to generate random numbers from sources provided by the operating system.

The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the secrets module.

M. Matsumoto and T. Nishimura, “Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator”, ACM Transactions on Modeling and Computer Simulation Vol. 8, No. 1, January pp.3–30 1998.

Complementary-Multiply-with-Carry recipe for a compatible alternative random number generator with a long period and comparatively simple update operations.

Bookkeeping functionsВ¶

Initialize the random number generator.

If a is an int, it is used directly.

With version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for str and bytes generates a narrower range of seeds.

Changed in version 3.2: Moved to the version 2 scheme which uses all of the bits in a string seed.

Return an object capturing the current internal state of the generator. This object can be passed to setstate() to restore the state.

random. setstate ( state ) В¶

Functions for bytesВ¶

Generate n random bytes.

This method should not be used for generating security tokens. Use secrets.token_bytes() instead.

New in version 3.9.

Functions for integersВ¶

Changed in version 3.2: randrange() is more sophisticated about producing equally distributed values. Formerly it used a style like int(random()*n) which could produce slightly uneven distributions.

random. getrandbits ( k ) В¶

Returns a non-negative Python integer with k random bits. This method is supplied with the MersenneTwister generator and some other generators may also provide it as an optional part of the API. When available, getrandbits() enables randrange() to handle arbitrarily large ranges.

Changed in version 3.9: This method now accepts zero for k.

Functions for sequencesВ¶

If neither weights nor cum_weights are specified, selections are made with equal probability. If a weights sequence is supplied, it must be the same length as the population sequence. It is a TypeError to specify both weights and cum_weights.

The weights or cum_weights can use any numeric type that interoperates with the float values returned by random() (that includes integers, floats, and fractions but excludes decimals). Weights are assumed to be non-negative and finite. A ValueError is raised if all weights are zero.

New in version 3.6.

Changed in version 3.9: Raises a ValueError if all weights are zero.

Shuffle the sequence x in place.

To shuffle an immutable sequence and return a new shuffled list, use sample(x, k=len(x)) instead.

Deprecated since version 3.9, will be removed in version 3.11: The optional parameter random.

Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).

Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.

If the sample size is larger than the population size, a ValueError is raised.

Changed in version 3.9: Added the counts parameter.

Real-valued distributionsВ¶

The following functions generate specific real-valued distributions. Function parameters are named after the corresponding variables in the distribution’s equation, as used in common mathematical practice; most of these equations can be found in any statistics text.

Return the next random floating point number in the range [0.0, 1.0).

Return a random floating point number N such that low N high and with the specified mode between those bounds. The low and high bounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.

random. expovariate ( lambd ) В¶

Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called “lambda”, but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative.

The probability distribution function is:

Normal distribution, also called the Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function defined below.

Multithreading note: When two threads call this function simultaneously, it is possible that they will receive the same return value. This can be avoided in three ways. 1) Have each thread use a different instance of the random number generator. 2) Put locks around all calls. 3) Use the slower, but thread-safe normalvariate() function instead.

Log normal distribution. If you take the natural logarithm of this distribution, you’ll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero.

Normal distribution. mu is the mean, and sigma is the standard deviation.

mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi.

random. paretovariate ( alpha ) В¶

Pareto distribution. alpha is the shape parameter.

Weibull distribution. alpha is the scale parameter and beta is the shape parameter.

Alternative GeneratorВ¶

Class that implements the default pseudo-random number generator used by the random module.

Class that uses the os.urandom() function for generating random numbers from sources provided by the operating system. Not available on all systems. Does not rely on software state, and sequences are not reproducible. Accordingly, the seed() method has no effect and is ignored. The getstate() and setstate() methods raise NotImplementedError if called.

Notes on ReproducibilityВ¶

Sometimes it is useful to be able to reproduce the sequences given by a pseudo-random number generator. By re-using a seed value, the same sequence should be reproducible from run to run as long as multiple threads are not running.

Most of the random module’s algorithms and seeding functions are subject to change across Python versions, but two aspects are guaranteed not to change:

If a new seeding method is added, then a backward compatible seeder will be offered.

The generator’s random() method will continue to produce the same sequence when the compatible seeder is given the same seed.

How can I randomly select an item from a list?

How do I retrieve an item at random from the following list?

How to randomize list in python. Смотреть фото How to randomize list in python. Смотреть картинку How to randomize list in python. Картинка про How to randomize list in python. Фото How to randomize list in python

18 Answers 18

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

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:

How to randomize list in python. Смотреть фото How to randomize list in python. Смотреть картинку How to randomize list in python. Картинка про How to randomize list in python. Фото How to randomize list in python

How to randomize list in python. Смотреть фото How to randomize list in python. Смотреть картинку How to randomize list in python. Картинка про How to randomize list in python. Фото How to randomize list in python

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.

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.

How to randomize list in python. Смотреть фото How to randomize list in python. Смотреть картинку How to randomize list in python. Картинка про How to randomize list in python. Фото How to randomize list in python

If you also need the index, use random.randrange

As of Python 3.6 you can use the secrets module, which is preferable to the random module for cryptography or security uses.

To print a random element from a list:

To print a random index:

For details, see PEP 506.

I propose a script for removing randomly picked up items off a list until it is empty:

Maintain a set and remove randomly picked up element (with choice ) until list is empty.

Three runs give three different answers:

How to randomize list in python. Смотреть фото How to randomize list in python. Смотреть картинку How to randomize list in python. Картинка про How to randomize list in python. Фото How to randomize list in python

How to randomize list in python. Смотреть фото How to randomize list in python. Смотреть картинку How to randomize list in python. Картинка про How to randomize list in python. Фото How to randomize list in python

For this question, it works the same as the accepted answer ( import random; random.choice() ), but I added it because the programmer may have imported NumPy already (like me)

And also there are some differences between the two methods that may concern your actual use case.

For reproducibility, you can do:

How to randomize list in python. Смотреть фото How to randomize list in python. Смотреть картинку How to randomize list in python. Картинка про How to randomize list in python. Фото How to randomize list in python

If you need the index, just use:

random.choice does the same:)

How to randomize list in python. Смотреть фото How to randomize list in python. Смотреть картинку How to randomize list in python. Картинка про How to randomize list in python. Фото How to randomize list in python

How to randomly select an item from a list?

Assume I have the following list:

What is the simplest way to retrieve an item at random from this list?

If you want close to truly random, then I suggest secrets.choice from the standard library (New in Python 3.6.):

If you want a deterministic pseudorandom selection, use the choice function (which is actually a bound method on a Random object):

It seems random, but it’s actually not, which we can see if we reseed it repeatedly:

A comment:

Well, yes you can pass it a «seed» argument, but you’ll see that the SystemRandom object simply ignores it:

Python: Select Random Element from a List

How to randomize list in python. Смотреть фото How to randomize list in python. Смотреть картинку How to randomize list in python. Картинка про How to randomize list in python. Фото How to randomize list in python

In this tutorial, you’ll learn how to use Python to choose a random element from a list. You’ll learn how to do this by choosing a random element from a list with substitution, without substitution, and how to replicate you results. You’ll also learn how to change the weighting of choices made.

The Quick Answer: Use random.choice()

How to randomize list in python. Смотреть фото How to randomize list in python. Смотреть картинку How to randomize list in python. Картинка про How to randomize list in python. Фото How to randomize list in python

Table of Contents

What is the Python Random Module?

The module comes with a number of helpful functions that allow us to randomly select or sample from a Python list. It also provides a seed generator which allows us to easily replicate our results time and time again, allowing is the opportunity to review results or troubleshoot any problems in our code.

Pick a Random Element from a List in Python

The simplest way to use Python to select a single random element from a list in Python is to use the random.choice() function. The function takes a single parameter – a sequence. In this case, our sequence will be a list, though we could also use a tuple.

Let’s see how we can use the method to choose a random element from a Python list:

We can see here that the choice() function selects one random item from our list.

The function expects the function to be non-empty. So,what happens when we pass in an empty list? The function will raise an IndexError and the program will fail unless the error is handled.

Let’s see what this looks like:

In the next section, you’ll learn how to use Python to choose a number of random elements without replacement.

Pick Random Elements from a List in Python without Replacement

In this section, you’ll learn how to use Python to select multiple random elements from a list without replacement. What does it mean to select without replacement? Sampling without replacement refers to only being able to pick a certain element a single time.

To use Python to select random elements without replacement, we can use the random.sample() function. The function accepts two parameters: the list to sample from and the number of items to sample.

Let’s see how we can use the random.sample() method to select multiple random elements from a list:

We can see that by passing in the value of 2 (for the keyword argument, k ) that two items are returned.

We can also use the random.sample() function to randomize the items in our list. We can do this by simply sampling all the items in the list.

Check out my tutorial on how to randomize Python list elements to learn more ways to accomplish this.

In the next section, you’ll learn how to use Python to pick random elements from a list with replacement.

Pick Random Elements from a List in Python with Replacement

There may also be times that you want to choose random items from a Python list with replacement. This means that an item can be chosen more than a single time. This has many useful applications, including in statistics.

Let’s see how we can select items with replacement in Python:

We can see in the example above, that the value 5 was returned twice, even though it exists only once in our list.

Let’s see what happens when the number for k exceeds the number of items in the list:

We can see that by setting the value of k to be greater than the length of the list, that the list that gets returned is larger than our original list.

In the next section, you’ll learn how to pick random elements with given weights in a list in Python.

Pick Weighted Random Elements from a List in Python with Replacement

There may be times when you want certain items to carry more weight than other items. This means that when selecting random items, you may want some items to have a higher likelihood of being chosen.

We can change the weights of our items by passing in an array into the weights= parameter. Before diving into how this works, we can imagine that by default an array of equal weights is used. By changing the relative weights, we can specify how much more likely we want an item to be chosen.

Let’s see how we can use Python to give an item a ten times higher likelihood of being chosen than other items in a list:

In the next section, you’ll learn how to reproduce results when selecting random elements.

Using Random Seed to Reproduce Results when Selecting Random Elements

A very useful element in developing random results, is (ironically) the ability to reproduce results. This can help others replicate your results and can help significantly in troubleshooting your work as well.

The Python random module includes the concept of a “seed”, which generates a random number generator. This allows us to replicate results.

Let’s see how we can use the random seed() function to reproduce our results:

If we were to re-run this program, we would return the same values each time.

Conclusion

To learn more about the Python random module, check out the official documentation here.

Additional Resources

To learn more about similar topics, check out the tutorials below:

Python: Shuffle a List (Randomize Python List Elements)

How to randomize list in python. Смотреть фото How to randomize list in python. Смотреть картинку How to randomize list in python. Картинка про How to randomize list in python. Фото How to randomize list in python

Knowing how to shuffle a list and produce a random result is an incredibly helpful skill. For example, it can be incredibly helpful in developing a Python game where you need to choose a random result. It can also have immensely helpful applications in data-related work, where you may need to pull random results.

The Quick Answer: Use random.shuffle()

How to randomize list in python. Смотреть фото How to randomize list in python. Смотреть картинку How to randomize list in python. Картинка про How to randomize list in python. Фото How to randomize list in python

Table of Contents

Both functions return a list that is randomly sorted, but how they return them is different:

random.sample() can also be used to shuffle strings and tuples, as it creates a new list, thereby allowing you to work on immutable data types.

Now, let’s dive into how to shuffle a list in Python!

Shuffle a Python List and Re-assign It to Itself

The random.shuffle() function makes it easy to shuffle a list’s items in Python. Because the function works in-place, we do not need to reassign the list to itself, but it allows us to easily randomize list elements.

Let’s take a look at what this looks like:

What we’ve done here is:

Keep in mind, if you’re following along with the example above, your randomly sorted list will probably look different!

In the next section, you’ll learn how to use the random.sample() function to randomize a list in Python.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Shuffle a Python List and Assign It to a New List

The random.sample() function is used to sample a set number of items from a sequence-like object in Python. The function picks these items randomly.

Let’s take a quick look at what the function looks like:

In this case, the iterable will be the list we want to shuffle, and k refers to the number of items we want to select. Because we want to return the full list in a random order, we will pass in the length of the list into the k parameter.

Let’s take a look at how we’ve managed to randomize our Python list elements:

In the next section, you’ll learn how to reproduce a shuffled list result in Python.

Want to learn how to pretty print a JSON file using Python? Learn three different methods to accomplish this using this in-depth tutorial here.

Reproduce a Shuffled Python List Result

When working with random results, there may be times when you want to be able to reproduce a result. In this example below, you’ll learn how to be able to reproduce a shuffled list.

We will use the random.seed() function to generate a result that is reproducible.

Let’s take a look at what this looks like:

In the next section, you’ll learn how to shuffle a Python list of lists.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Shuffle a Python List of Lists

In Python, you’ll often encounter multi-dimensional lists, often referred to as lists of lists. We can easily do this using a for loop. By looping over each list in the list of lists, we can then easily apply the random.shuffle() function to randomize each sublist’s elements.

Let’s take a look at what this looks like:

While we could also accomplish this using a list comprehension, the syntax of not re-assigning the list comprehension is a bit awkward and not as intuitive. For this reason, we’ve opted to use a for loop here as we should always be striving for readability.

In the next section, you’ll learn how to shuffle multiple lists with the same order of shuffling.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Shuffle Multiple Lists with the Same Order of Shuffling

Let’s say you have two lists: one that contains the type of fruit and the other the number of that type of fruit you have. You want to shuffle the lists but you want the referential integrity to remain true (meaning that index 0 of both lists would be shuffled to the same index in the shuffled result).

In order to accomplish this, we’ll:

Let’s take a look at how we can do this:

We can see that we’ve made good use of both the zip() function as well as Python list comprehensions to make this happen.

Need to automate renaming files? Check out this in-depth guide on using pathlib to rename files. More of a visual learner, the entire tutorial is also available as a video in the post!

Conclusion

To learn more about the random library, check out the official documentation here.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *