Chuyển tới nội dung
Home » Import Random Python 3 | Common Issues And Solutions With Randint

Import Random Python 3 | Common Issues And Solutions With Randint

Python Tutorial: Generate Random Numbers and Data Using the random Module

Random Module in Python Examples

Let’s discuss some common operations performed by Random module in Python.

Example 1: Printing a random value from a list in Python.

This code uses the

random

module to select a random element from the list

list1

using the

random.choice()

function. It prints a random element from the list, demonstrating how to pick a random item from a sequence in Python.

Python3


import


random


random.seed(


print


(random.random())


print


(random.random())

Output

0.6229016948897019
0.7417869892607294

Generate Random Numbers in Python

random.randint() method is used to generate random integers between the given range.

Syntax: randint(start, end)

Example: Creating random integers

This code uses the ‘

random'

module to generate random integers within specific ranges. It first generates a random integer between 5 and 15 (inclusive) and then between -10 and -2 (inclusive). The generated integers are printed with appropriate formatting.

Python Tutorial: Generate Random Numbers and Data Using the random Module
Python Tutorial: Generate Random Numbers and Data Using the random Module

Python3


import


random


list1


print


(random.choice(list1))


string


"geeks"


print


(random.choice(string))


tuple1


print


(random.choice(tuple1))

Example 2: Python random.sample() function is used to return a random item from a list, tuple, or string.

Syntax: random.sample(sequence, length)

This code utilizes the

sample

function from the ‘

random'

module to obtain random samples from various data types. It selects three random elements without replacement from a list, a tuple, and a string, demonstrating its versatility in generating distinct random samples. With each execution, the selected elements will differ, providing random subsets from the input data structures.

List of all the functions Python Random Module

There are different random functions in the Random Module of Python. Look at the table below to learn more about these functions:

seed() Initialize the random number generator
getstate() Returns an object with the current internal state of the random number generator
setstate() Used to restore the state of the random number generator back to the specified state
getrandbits() Return an integer with a specified number of bits
randrange() Returns a random number within the range
randint() Returns a random integer within the range
choice() Returns a random item from a list, tuple, or string
choices() Returns multiple random elements from the list with replacement
sample() Returns a particular length list of items chosen from the sequence
random() Generate random floating numbers
uniform() Return a random floating number between two numbers both inclusive
triangular() Return a random floating point number within a range with a bias towards one extreme
betavariate() Return a random floating point number with beta distribution
expovariate() Return a random floating point number with exponential distribution
gammavariate() Return a random floating point number with a gamma distribution
gauss() Return a random floating point number with Gaussian distribution
lognormvariate() Return a random floating point number with a log-normal distribution
normalvariate() Return a random floating point number with normal distribution
vonmisesvariate() Return a random floating point number with von Mises distribution or circular normal distribution
paretovariate() Return a random floating point number with a Pareto distribution
weibullvariate() Return a random floating point number with Weibull distribution
Random number generator in Python
Random number generator in Python

Code – Password Generator Using Random Module

As we are done studying about the random module and what it can do with the function that it offers. Let us implement it in a real-world application by designing a password generator.

import random import string # Generating Random Passwords def generatePassword(n): characters = string.ascii_letters + string.digits + string.punctuation password = ”.join(random.choices(characters, k=n)) return password print(“Enter the length of password you want to generate:-“) while True: password = generatePassword(int(input())) print(“Your password is: “,password) inp = input(“Do you agree with password. Press Y or N – “) if inp == “Y”: print(“Password was changed!”) break

Output:


Enter if you want to generate password:- Your password is: vB%N&N[TG[eK6zF#Nl-@ Do you agree with password. Press Y or N - Y Password was changed!

Explanation:Password generator function takes an input that provides the length of password to be generated. It forms a string consisting of numbers, letters and punctuations such that the string is interpreted as the sequence to pick the random values from in it. choice() function is used giving the length of password to generate the password. As the prompt shows, if we want to go ahead with the password, we can go ahead or break out.

ConclusionThe random module in Python is a valuable resource for introducing randomness into your programs and projects. Whether you’re building games, conducting simulations, or need to make probabilistic decisions, this module provides a robust set of functions to help you achieve your goals. From generating random numbers with different distributions to shuffling sequences and selecting random elements, the “random” module’s capabilities are vast and versatile.

As you continue to explore Python’s random module, remember to consider the specific requirements of your project. Carefully select the appropriate randomization technique, distribution, or function to ensure that randomness serves its intended purpose effectively. With the “random” module in your programming arsenal, you can add unpredictability and excitement to your Python applications.

How to use random.randint()

Syntax:


random.randint(start, stop)

This function returns a random integer between a given start and stop integer.

Parameters:

It takes two parameters. Both are mandatory.


  • start

    : It is the start position of a range. The default value is 0 if not specified.

  • stop

    : It is the end position of a range.

Return value:

It will generate any random integer number from the inclusive range. The

randint(start, stop)

consider both the start and stop numbers while generating random integers

How to use Python

randint()

and

randrange()

to get random integers

  1. Import random module

    Use Python’s random module to work with random data generation.

    import it using a

    import random

    statement.

  2. Use randint() Generate random integer

    Use a


    random.randint()

    function to get a random integer number from the inclusive range. For example,

    random.randint(0, 10)

    will return a random number from [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9, 10].

  3. Use the randrnage() function to generate a random integer within a range

    Use a


    random.randrange()

    function to get a random integer number from the given exclusive range by specifying the increment. For example,

    random.randrange(0, 10, 2)

    will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).

random.randint() example of generating random number


import random # random integer from 0 to 9 num1 = random.randint(0, 9) print(num1) # output 5 # Random integer from 10 to 100 num2 = random.randint(10, 100) print(num2) # Output 84

Note: You cannot use float numbers in

randint()

. It will raise a ValueError (

non-integer stop for randrange()

) if you use non-integer numbers. Please, read how to generate a random float number within a range.

Generate random numbers in Python 🎲
Generate random numbers in Python 🎲

Examples¶

Basic examples:

>>> random() # Random float: 0.0 <= x < 1.0 0.37444887175646646 >>> uniform(2.5, 10.0) # Random float: 2.5 <= x <= 10.0 3.1800146073117523 >>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds 5.148957571865031 >>> randrange(10) # Integer from 0 to 9 inclusive 7 >>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive 26 >>> choice([‘win’, ‘lose’, ‘draw’]) # Single random element from a sequence ‘draw’ >>> deck = ‘ace two three four’.split() >>> shuffle(deck) # Shuffle a list >>> deck [‘four’, ‘two’, ‘ace’, ‘three’] >>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement [40, 10, 50, 30]

Simulations:

>>> # Six roulette wheel spins (weighted sampling with replacement) >>> choices([‘red’, ‘black’, ‘green’], [18, 18, 2], k=6) [‘red’, ‘green’, ‘black’, ‘black’, ‘red’, ‘black’] >>> # Deal 20 cards without replacement from a deck >>> # of 52 playing cards, and determine the proportion of cards >>> # with a ten-value: ten, jack, queen, or king. >>> deal = sample([‘tens’, ‘low cards’], counts=[16, 36], k=20) >>> deal.count(‘tens’) / 20 0.15 >>> # Estimate the probability of getting 5 or more heads from 7 spins >>> # of a biased coin that settles on heads 60% of the time. >>> sum(binomialvariate(n=7, p=0.6) >= 5 for i in range(10_000)) / 10_000 0.4169 >>> # Probability of the median of 5 samples being in middle two quartiles >>> def trial(): … return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500 … >>> sum(trial() for i in range(10_000)) / 10_000 0.7958

Example of statistical bootstrapping using resampling with replacement to estimate a confidence interval for the mean of a sample:

# https://www.thoughtco.com/example-of-bootstrapping-3126155 from statistics import fmean as mean from random import choices data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95] means = sorted(mean(choices(data, k=len(data))) for i in range(100)) print(f’The sample mean of {mean(data):.1f} has a 90% confidence ‘ f’interval from {means[5]:.1f} to {means[94]:.1f}’)

Example of a resampling permutation test to determine the statistical significance or p-value of an observed difference between the effects of a drug versus a placebo:

# Example from “Statistics is Easy” by Dennis Shasha and Manda Wilson from statistics import fmean as mean from random import shuffle drug = [54, 73, 53, 70, 73, 68, 52, 65, 65] placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46] observed_diff = mean(drug) – mean(placebo) n = 10_000 count = 0 combined = drug + placebo for i in range(n): shuffle(combined) new_diff = mean(combined[:len(drug)]) – mean(combined[len(drug):]) count += (new_diff >= observed_diff) print(f'{n} label reshufflings produced only {count} instances with a difference’) print(f’at least as extreme as the observed difference of {observed_diff:.1f}.’) print(f’The one-sided p-value of {count / n:.4f} leads us to reject the null’) print(f’hypothesis that there is no difference between the drug and the placebo.’)

Simulation of arrival times and service deliveries for a multiserver queue:

from heapq import heapify, heapreplace from random import expovariate, gauss from statistics import mean, quantiles average_arrival_interval = 5.6 average_service_time = 15.0 stdev_service_time = 3.5 num_servers = 3 waits = [] arrival_time = 0.0 servers = [0.0] * num_servers # time when each server becomes available heapify(servers) for i in range(1_000_000): arrival_time += expovariate(1.0 / average_arrival_interval) next_server_available = servers[0] wait = max(0.0, next_server_available – arrival_time) waits.append(wait) service_duration = max(0.0, gauss(average_service_time, stdev_service_time)) service_completed = arrival_time + wait + service_duration heapreplace(servers, service_completed) print(f’Mean wait: {mean(waits):.1f} Max wait: {max(waits):.1f}’) print(‘Quartiles:’, [round(q, 1) for q in quantiles(waits)])

See also

Statistics for Hackers a video tutorial by Jake Vanderplas on statistical analysis using just a few fundamental concepts including simulation, sampling, shuffling, and cross-validation.

Economics Simulation a simulation of a marketplace by Peter Norvig that shows effective use of many of the tools and distributions provided by this module (gauss, uniform, sample, betavariate, choice, triangular, and randrange).

A Concrete Introduction to Probability (using Python) a tutorial by Peter Norvig covering the basics of probability theory, how to write simulations, and how to perform data analysis using Python.

Generating Random Numbers

Now that we have some idea about the python random module, we will be looking at how to generate numbers of different types using the methods of random library.

Float Value Between 0 and 1:-

In the below code mentioned, we can use the random() function to generate a float value between the range 0.0 and 1.0 such that value must me greater than or equal to 0.0 and strictly lesser than 1.0.

Syntax:


import random # Generating random float print(random.random())

Output:


0.23671507374354974

Integer Between Input Range:-

If we want to generate a random integer in a certain range then the randint() function proves to be the ideal that takes in two inputs, suppose a and b, and generates one between the two integers. It includes a and b as well in the result.

Syntax:


import random #Generating Random integer print(random.randint(1, 10))

Output:

Float Between Input Range:-

Similarly to generating integers between two input values, assumingly, a and b, we can generate a float value between the two inputs using uniform() function. The code below can be referred to for same.

Syntax:


import random #Generating Random float print(random.uniform(1, 10))

Output:


7.581086804968139

How to import a random number in python
How to import a random number in python

Using randint in Loops

One of the powerful ways to use

randint()

is within loops. This allows you to generate multiple random numbers at once. For instance, if you need to generate a list of 5 random numbers between 1 and 10, you can use a for loop with

randint()

:


import random random_numbers = [random.randint(1, 10) for _ in range(5)] print(random_numbers) # Output: # (A list of 5 random numbers between 1 and 10)

In this code, we’re using a for loop to generate a list of 5 random numbers. The

random.randint(1, 10)

function is called 5 times, once for each iteration of the loop, generating a new random number each time. The result is a list of 5 random integers.

These examples demonstrate how you can use Python’s

randint()

function in more complex ways to suit your needs. By adjusting the range and using loops, you can generate a variety of random number sequences.

Random negative integer

Let’s see how to generate a random negative integer between -60 to -6.


import random singed_int = random.randrange(-60, -6) print(singed_int) # Output -16

Generate random positive or negative integer


import random for i in range(5): print(random.randint(-10, 10), end=' ') # Output 10 -1 5 -10 -7

Randomly generate 1 or -1


import random num = random.choice([-1, 1]) print(num)

Note: we used random.choice() to choose a single number from the list of numbers. Here our list is

[-1, 1]

.

Bai19: Hàm lấy số ngẫu nhiên - random python - Tự học lập trình python
Bai19: Hàm lấy số ngẫu nhiên – random python – Tự học lập trình python

What is a Python Random Module?

Random module comes built-in with python which means that we do not need to install a package but just import and use it on the go. Python Random Module is useful in implementing a randomization algorithm. It can be used for generating integers from a specified range to pick the number from. Also, we have the feature to choose from a sequence of numbers of choice we can pick from a list of elements.

However, it generates the numbers in a pseudorandom manner that is not completely random if we deep dive further into its working mechanism under the hood but still remains effective for usage. Different functions from the Python Random Module are going to be discussed in this article with examples and explanations for each.

Seeding can be performed using seed() function where on seeding, the same value will be generated. It is used as a tool to initialize the value generator to reset in an algorithmic manner that once seeded, the sequence of values obtained remains the same.

Given below is an example of seeding in Python Random Module.

Example of Python Random Module:

import random # Seed the random number generator random.seed(2) # Generate 4 random numbers for i in range(4): print(random.random()) random.seed(2)

Output:


0.9560342718892494 0.9560342718892494 0.9560342718892494 0.9560342718892494

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 −

[10, 5, 21, 1, 17]

How to Generate Different Random Numbers in Python 3
How to Generate Different Random Numbers in Python 3

Generating Random Numbers

Now that we have some idea about the python random module, we will be looking at how to generate numbers of different types using the methods of random library.

Float Value Between 0 and 1:-

In the below code mentioned, we can use the random() function to generate a float value between the range 0.0 and 1.0 such that value must me greater than or equal to 0.0 and strictly lesser than 1.0.

Syntax:


import random # Generating random float print(random.random())

Output:


0.23671507374354974

Integer Between Input Range:-

If we want to generate a random integer in a certain range then the randint() function proves to be the ideal that takes in two inputs, suppose a and b, and generates one between the two integers. It includes a and b as well in the result.

Syntax:


import random #Generating Random integer print(random.randint(1, 10))

Output:

Float Between Input Range:-

Similarly to generating integers between two input values, assumingly, a and b, we can generate a float value between the two inputs using uniform() function. The code below can be referred to for same.

Syntax:


import random #Generating Random float print(random.uniform(1, 10))

Output:


7.581086804968139

When to Use the Random Module in Python?

The random module provides functions that help in making random selections and generating random values. Hence, we can use the random module in Python in the following cases.

  • If you want the computer to pick a random number in a given range, pick a random element from a Python list, pick a random card from a deck, flip a coin, etc, you can use the random module in Python.
  • You can also use the random module to create random strings while choosing passwords to make your password database more secure or power a random page feature of your website.
  • Random modules provide functions to shuffle container objects like lists. Hence, you can use the random module to shuffle a list.
Generating random numbers between 1 and 100 using python #python
Generating random numbers between 1 and 100 using python #python

Code – Password Generator Using Random Module

As we are done studying about the random module and what it can do with the function that it offers. Let us implement it in a real-world application by designing a password generator.

import random import string # Generating Random Passwords def generatePassword(n): characters = string.ascii_letters + string.digits + string.punctuation password = ”.join(random.choices(characters, k=n)) return password print(“Enter the length of password you want to generate:-“) while True: password = generatePassword(int(input())) print(“Your password is: “,password) inp = input(“Do you agree with password. Press Y or N – “) if inp == “Y”: print(“Password was changed!”) break

Output:


Enter if you want to generate password:- Your password is: vB%N&N[TG[eK6zF#Nl-@ Do you agree with password. Press Y or N - Y Password was changed!

Explanation:Password generator function takes an input that provides the length of password to be generated. It forms a string consisting of numbers, letters and punctuations such that the string is interpreted as the sequence to pick the random values from in it. choice() function is used giving the length of password to generate the password. As the prompt shows, if we want to go ahead with the password, we can go ahead or break out.

ConclusionThe random module in Python is a valuable resource for introducing randomness into your programs and projects. Whether you’re building games, conducting simulations, or need to make probabilistic decisions, this module provides a robust set of functions to help you achieve your goals. From generating random numbers with different distributions to shuffling sequences and selecting random elements, the “random” module’s capabilities are vast and versatile.

As you continue to explore Python’s random module, remember to consider the specific requirements of your project. Carefully select the appropriate randomization technique, distribution, or function to ensure that randomness serves its intended purpose effectively. With the “random” module in your programming arsenal, you can add unpredictability and excitement to your Python applications.

Table of contents

  • How to use random.randint()
  • random.randrange() to generate random integers within a range
  • Random negative integer
  • Generate a list of random integer numbers
  • Generate a secure random integer
  • Create a multidimensional array of random integers
  • Points to remember about randint() and randrange()
  • Next Steps
Giáo sư Toán dạy bạn đánh Tài Xỉu thắng 100%, quay Gacha bách phát bách trúng
Giáo sư Toán dạy bạn đánh Tài Xỉu thắng 100%, quay Gacha bách phát bách trúng

Code Example For Random Module in Python

The following code example uses the

choice()

function to count the number of heads and tails in 10000 flips of a coin. For this, we define a dictionary named outcomes to store the number of heads and tails. Next, we use the

keys()

method of the Python dictionary to get the list

["heads", "tails"]

. After this, we use the

choice()

function to select one of the values from the list randomly and update the outcomes dictionary according to the output.


import random import itertools outcomes = { 'heads':0, 'tails':0, } sides = outcomes.keys() for i in range(10000): outcomes[ random.choice(sides) ] += 1 print 'Heads:', outcomes['heads'] print 'Tails:', outcomes['tails']

There are only two outcomes allowed, so rather than use numbers and convert them, the values “

heads”

and

“tails”

are used with the

choice()

function.

The results are tabulated in a dictionary using the outcome names as keys.


Heads: 4984 Tails: 501

Python3


from


random


import


sample


list1


print


(sample(list1,


))


list2


print


(sample(list2,


))


list3


"45678"


print


(sample(list3,


))

Output

[4, 2, 3]
[4, 7, 8]
[‘6’, ‘4’, ‘8’]

Máy tính có random thật không?
Máy tính có random thật không?

Python Random random() Method

The random.random() function generates random floating numbers in the range of 0.1, and 1.0. It takes no parameters and returns values uniformly distributed between 0 and 1. There are various functions associated with the random module are:

  1. Python random()
  2. Python randrange()
  3. Python randint()
  4. Python seed()
  5. Python choice(), and many more. We are only demonstrating the use of the random() function in this article.

Notes on Reproducibility¶

Sometimes it is useful to be able to reproduce the sequences given by a pseudo-random number generator. By reusing 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.

Go 1.22 is bringing about a new future for the language.
Go 1.22 is bringing about a new future for the language.

Bookkeeping functions¶

random.seed(a=None, version=2)¶

Initialize the random number generator.

If a is omitted or


None

, the current system time is used. If randomness sources are provided by the operating system, they are used instead of the system time (see the

os.urandom()

function for details on availability).

If a is an int, it is used directly.

With version 2 (the default), a


str

,

bytes

, or

bytearray

object gets converted to an

int

and all of its bits are used.

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.

random.getstate()¶

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)¶

state should have been obtained from a previous call to


getstate()

, and

setstate()

restores the internal state of the generator to what it was at the time

getstate()

was called.

Python3


from


random


import


random


print


(random())

Output:

0.41941790721207284

Another way to write the same code.

Chapter 1: Data Types/Reading Data
Chapter 1: Data Types/Reading Data

Generate a secure random integer

Above all, examples are not cryptographically secure. The cryptographically secure random generator generates random numbers using synchronization methods to ensure that no two processes can obtain the same number simultaneously.

If you are producing random numbers for a security-sensitive application, then you must use this approach.

Use the secrets module if you are using a Python version higher than 3.6.


import secrets # secure random integer # from 0 to 10 secure_num = secrets.randbelow(10) print(secure_num) # Output 5

If you are using Python version less than 3.6, then use the

random.SystemRandom().randint()

or

random.SystemRandom().randrange()

functions.

Python3


import


random


random.seed(


10


print


(random.random())


random.seed(


10


print


(random.random())

Output:

0.5714025946899135
0.5714025946899135

Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated :
26 Apr, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

I’m having problems with Python’s import random function. It seems that

import random

and

from random import random

are importing different things. I am currently using Python 2.7.3


Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> random() Traceback (most recent call last): File " ", line 1, in

random() NameError: name 'random' is not defined >>> random.randint(1,5) Traceback (most recent call last): File " ", line 1, in

random.randint(1,5) NameError: name 'random' is not defined >>> import random >>> random() Traceback (most recent call last): File " ", line 1, in

random() TypeError: 'module' object is not callable >>> random.randint(1,5) 2 >>> from random import random >>> random() 0.28242411635200193 >>> random.randint(1,5) Traceback (most recent call last): File " ", line 1, in

random.randint(1,5) AttributeError: 'builtin_function_or_method' object has no attribute 'randint' >>>

Last Updated on October 18, 2023 by Ankit Kochar

The Python programming language offers a wide range of modules and libraries to simplify various tasks. Among these, the random module in Python stands out as a powerful tool for generating random numbers, making decisions based on chance, and implementing various probabilistic algorithms. Whether you’re developing a game, conducting simulations, or adding randomness to your applications, the random module is an essential component of your Python toolkit.

In this article, we will dive into the world of the Python random module. We’ll explore its capabilities, functions, and how you can harness its power to introduce randomness into your Python programs. From generating random integers to shuffling lists and selecting random elements, this module offers a plethora of features that can enhance the versatility of your Python projects.

3 Ways to Make a Custom AI Assistant | RAG, Tools, & Fine-tuning
3 Ways to Make a Custom AI Assistant | RAG, Tools, & Fine-tuning

Random Functions in Python

The Random module contains some very useful functions. The most commonly used functions in the random module in Python are the

randint()

function, the

random()

function, the

choice()

function, the

randrange()

function, and the

shuffle()

function. Let us discuss each of these functions one by one.

The randint() Function in Python

We can use the

randint()

function in the Python random module to generate random numbers within a range. The

randint()

function takes two numbers as its input argument. The first input argument is the start of the range and the second input argument is the end of the range. After execution, the

randint()

function returns a random integer within the given range.

If you want a random integer, you can use the

randint()

function. For instance, you can generate random integers between 1 and 10 as shown in the following example.


import random integer1=random.randint(1,10) integer2=random.randint(1,10) integer3=random.randint(1,10) integer4=random.randint(1,10) print("The random integers between 1 and 10 are:",integer1, integer2, integer3, integer4)

Output:


The random integers between 1 and 10 are: 9 8 10 1

In the above code, we have created four random integers between 1 and 10. You can observe that the

randint()

function generates a different integer each time we execute it. However, this is not guaranteed. It is also possible that the function may generate the same number on consecutive executions. However, it is sure that the numbers generated afterward have no relation whatsoever with the previous numbers generated using the

randint()

function.

In the above code, you should make sure that the first input argument in the

randint()

function should always be less than the second input argument. Otherwise, the program runs into an error. You can observe this in the following example.


import random integer1=random.randint(10,1) print("The random integers between 1 and 10 is:",integer1)

Output:

In the above image, you can observe that the program runs into error if we pass the first input argument greater than the second input argument in the

randint()

function.

The random() Function

The

random()

function in the random module is used to generate random numbers between 0 and 1. When we execute the

random()

function, it returns a floating point number between 0 and 1. You can observe this in the following example.


import random number1=random.random() number2=random.random() number3=random.random() number4=random.random() print("The random numbers are:",number1, number2, number3, number4 )

Output:


The random numbers are: 0.2801382415422472 0.48619684476217817 0.5339393721250865 0.9565177646505902

In the above output, you can observe that the

random()

function generates a random value between 0 to 1 each time it is executed.

If you want a larger number, you can multiply the values generated from the

random()

function by a larger value. For example, to create a random number between 10 and 100, you can multiply the output of the

random()

function by 100 as shown below.


import random number1=random.random()*100 number2=random.random()*100 number3=random.random()*100 number4=random.random()*100 print("The random numbers are:",number1, number2, number3, number4 )

Output:


The random numbers are: 51.43882585961895 59.29311262613833 37.44226472488235 50.768817583443315

In the above example, we have created random numbers between 10 and 100 by multiplying the output of the

random()

function by 100. In a similar manner, you can multiply the output of the

random()

function by negative numbers to generate negative values.

The choice() Function

The

choice()

function is used to select a random element from a collection object like a list, set, tuple, etc. The function takes a collection object as its input argument and returns a random element.

For example, you can select a random color from a list of colors by passing the list of color names to the

choice()

function as input as shown in the following example.


import random colors=["red","green","blue","yellow","violet","indigo","orange"] print("The list of colors is:",colors) color=random.choice(colors) print("The randomly selected value from the list is:",color)

Output:


The list of colors is: ['red', 'green', 'blue', 'yellow', 'violet', 'indigo', 'orange'] The randomly selected value from the list is: orange

In the above example, we first created a list of seven color values. Then we passed it to the

choice()

function defined in the random module in Python to select a random value from the list.

If we pass an empty list to the

choice()

function, it runs into a Python IndexError exception as shown below.


import random colors=[] print("The list of colors is:",colors) color=random.choice(colors) print("The randomly selected value from the list is:",color)

Output:


IndexError: list index out of range

The choices() Function

We can use the

choices()

function defined in the random module in Python to select two or more elements randomly with replacement from a list. The

choices()

function takes the list of values as its first input argument and the values to be selected as the input for its parameter . After execution, it returns a list of selected values from the input container object.

For example, you can select three values from the list of colors using the

choices()

function as shown below.


import random colors=["red","green","blue","yellow","violet","indigo","orange"] print("The list of colors is:",colors) color=random.choices(colors,k=3) print("The randomly selected values from the list are:",color)

Output:


The list of colors is: ['red', 'green', 'blue', 'yellow', 'violet', 'indigo', 'orange'] The randomly selected values from the list are: ['blue', 'orange', 'orange']

In the above example, you can observe the output list of values contains the value

'orange'

twice. This is due to the reason that the

choices()

function makes a random selection with replacement. Hence, a value can be repeated two or more times in the output list.

If you pass the value

k=0

to the

choices()

function, it will return an empty list as shown below.


import random colors=["red","green","blue","yellow","violet","indigo","orange"] print("The list of colors is:",colors) color=random.choices(colors,k=0) print("The randomly selected values from the list are:",color)

Output:


The list of colors is: ['red', 'green', 'blue', 'yellow', 'violet', 'indigo', 'orange'] The randomly selected values from the list are: []

Even if we set k larger than the number of elements in the input list, the

choices()

function produces the output list as shown below.


import random colors=["red","green","blue","yellow","violet","indigo","orange"] print("The list of colors is:",colors) color=random.choices(colors,k=20) print("The randomly selected values from the list are:",color)

Output:


The list of colors is: ['red', 'green', 'blue', 'yellow', 'violet', 'indigo', 'orange'] The randomly selected values from the list are: ['yellow', 'orange', 'orange', 'violet', 'orange', 'violet', 'red', 'violet', 'green', 'violet', 'indigo', 'violet', 'yellow', 'red', 'red', 'indigo', 'red', 'red', 'green', 'green']

In this example, we have only seven elements in the input list. However, the

choices()

function has given a list containing 20 elements as its output. This is due to the reason that the

choices()

function makes a selection with replacement. Hence, an infinite number of selections can be made from the input list.

If the input list to the

choices()

function is empty, the

choices()

function creates an empty list when we ask it to select 0 elements from the list. You can observe this in the following example.


import random colors=[] print("The list of colors is:",colors) color=random.choices(colors,k=0) print("The randomly selected values from the list are:",color)

Output:


The list of colors is: [] The randomly selected values from the list are: []

In the above example, the input and output lists both are empty. However, if we try to select one or more elements from an empty list using the

choices()

function, the program will run into an error. You can observe this in the following example.


import random colors=[] print("The list of colors is:",colors) color=random.choices(colors,k=2) print("The randomly selected values from the list are:",color)

Output:


IndexError: list index out of range

In this example, we tried to select two elements from an empty list. Hence, the program runs into an

IndexError

exception.

The shuffle() Function

As the name suggests, the

shuffle()

function shuffles the elements in the list in place. The

shuffle()

function takes a list as an input argument. After execution, the elements of the list are shuffled in a random order as shown in the following example.


import random colors=["red","green","blue","yellow","violet","indigo","orange"] print("The list of colors is:",colors) random.shuffle(colors) print("The list of colors after shuffle is:",colors)

Output:


The list of colors is: ['red', 'green', 'blue', 'yellow', 'violet', 'indigo', 'orange'] The list of colors after shuffle is: ['green', 'indigo', 'blue', 'violet', 'yellow', 'orange', 'red']

In the above output, you can observe that the order of the elements in the colors list has changed after executing the

shuffle()

function.

The randrange() Function

The

randrange()

function in the Python random module is used to select a random element from a given range. It takes three numbers namely

start

,

stop

, and

step

as input argument. After execution, it generates a randomly selected element from the

range(start, stop, step)

. You can observe this in the following example.


import random number=random.randrange(0,100,20) print("The random number is:",number)

Output:


The random number is: 20

In the above example, the

randrange()

function will always generate one of the values from [0,20,40,60,80]. You can observe this in the following example.


import random print("The numbers are") for i in range(50): number=random.randrange(0,100,20) print(number, end=" ")

Output:


The numbers are 20 40 60 60 60 20 80 60 80 0 20 60 80 80 80 20 80 40 20 60 40 60 40 0 0 40 20 80 0 60 40 40 40 20 80 0 40 80 20 0 80 20 40 60 0 40 20 0 40 80

In the above example, you can observe that the values in the output are from the list

[0, 20, 40, 60, 80]

. What explains this behavior of the randrange() function?

Effectively, the

randrange()

function works as a combination of the

choice()

function and the

range()

function. First, it generates numbers in the given range with the given intervals using the

range()

function. To understand the working of the

range()

function, you can read this article on Python range. After generating numbers in the given range, it uses the

choice()

function to select a random value in the given range.

Create a multidimensional array of random integers

Python’s NumPy module has a

numpy.random

package to generate random data. To create a random multidimensional array of integers within a given range, we can use the following NumPy methods:


  • randint()

  • random_integers()

  • np.randint(low[, high, size, dtype])

    to get random integers array from low (inclusive) to high (exclusive).

  • np.random_integers(low[, high, size])

    to get random integer’s array between low and high, inclusive.

Now, Let see the example.

Generate a 4 x 4 array of ints between 10 and 50, exclusive:


import numpy # 4 x 4 array newArray = numpy.random.randint(10, 50, size=(4, 4)) print(newArray)

Output:

[[10 48 30 24] [13 46 30 11] [12 28 49 26] [30 18 49 35]]

Generate a 5 x 3 array of random integers between 60 and 100, inclusive.


import numpy # 3 x 5 array of ints newArray = numpy.random.random_integers(60, 100, size=(3, 5)) print(newArray)

Output:

[[63 76 95 93 75] [71 84 63 99 93] [65 64 66 69 92]]

How to Install requests module in Python 3 on Windows 10/8/7
How to Install requests module in Python 3 on Windows 10/8/7

Further Reading: Probability Theory and Statistical Analysis

If you’re interested in the theory behind random number generation, consider studying probability theory. And if you want to apply random number generation in data analysis, look into statistical analysis in Python. Both topics will provide a deeper understanding of the power and potential of Python’s

randint()

function.

Further Resources for Python Modules

For a more profound understanding of Python Modules, we have gathered several insightful resources for you:

  • Python Modules Fundamentals Covered – Dive deep into Python’s module caching and reload mechanisms.
  • Implementing Queues in Python – Dive into various queue types, including FIFO and LIFO, in Python.

  • Simplifying Random Data Generation in Python – Learn how to add randomness to your Python programs with “random.”

  • Python’s Random Module – Learn about the random module and generating random numbers with this Programiz guide.

  • How to Create Random Numbers in Python – A Medium article that delves into generating random numbers in Python.

  • Python’s Random Tutorial – A tutorial by Real Python covering topics related to generating random numbers in Python.

Explore these resources, and you’ll be taking another stride towards expertise in Python and taking your coding abilities to the next level.

Next Steps

I want to hear from you. What do you think of this article on

randint()

and

randrange()

? Or maybe I missed one of the usages of those two functions. Either way, let me know by leaving a comment below.

Also, try to solve the following exercise and quiz to have a better understanding of working with random data in Python.

  • Python random data generation Exercise to practice and master the random data generation techniques in Python.
  • Python random data generation Quiz to test your random data generation concepts.

Last Updated on October 18, 2023 by Ankit Kochar

The Python programming language offers a wide range of modules and libraries to simplify various tasks. Among these, the random module in Python stands out as a powerful tool for generating random numbers, making decisions based on chance, and implementing various probabilistic algorithms. Whether you’re developing a game, conducting simulations, or adding randomness to your applications, the random module is an essential component of your Python toolkit.

In this article, we will dive into the world of the Python random module. We’ll explore its capabilities, functions, and how you can harness its power to introduce randomness into your Python programs. From generating random integers to shuffling lists and selecting random elements, this module offers a plethora of features that can enhance the versatility of your Python projects.

Avoiding import loops in Python
Avoiding import loops in Python

Working with Sequences

The application of the Python Random module is not limited to single values such as integer or float as we can use it to work on sequences as well.

Random K Elements From List (Without Replacing)

In case we have a list container and we want to pick only k values from it such that all of them are randomly picked without replacement, we can use sample(l,k) where l is the list container with elements and k is the number of required elements.

Syntax:


import random items = [ 2, 3, 4, 5, 37, 8, 9, 10] print(random.sample(items, 3))

Output:


[37, 9, 5]

Random K Elements From List (With Replacing Items)

In such a scenario where a sequence and k random values need to be picked, replacing the element then choice() function is the alternative to the sample() function where the same element can be picked multiple times. Give Python Random K elements from list code is given below:-

Syntax:


import random items = [2, 3, 4, 25, 7, 38, 9] print(random.choices(items, k=3))

Output:


[2, 3, 3]

TL;DR: How Do I Use the randint Function in Python?

The randint function is part of Python’s random module, and it’s used to generate a random integer within a specified range. Here’s a simple example:


import random number = random.randint(1, 10) print(number) # Output: # (A random number between 1 and 10)

In this example, we’re using Python’s

random.randint()

function to generate a random number between 1 and 10. The

import random

line at the beginning is necessary because randint is part of the random module in Python. The function

random.randint(1, 10)

then generates a random integer within the range of 1 and 10.

If you’re interested in learning more about the randint function, including its more advanced uses and potential issues you might encounter, keep reading for a comprehensive exploration.

Table of Contents

  • Understanding Python’s randint Function
  • Expanding the Range of randint
  • Using randint in Loops
  • Exploring Alternatives to randint
  • Common Issues and Solutions with randint
  • Best Practices with randint
  • Understanding Random Number Generation in Python
  • Real-World Applications of Python’s randint
  • Further Reading: Probability Theory and Statistical Analysis
  • Wrapping Up: Python’s randint Function
AVOID Using: \
AVOID Using: \”import *\” At ALL Costs In Python

Python3


import


random


r1


random.randint(


15


print


"Random number between 5 and 15 is % s"


(r1))


r2


random.randint(


10


print


"Random number between -10 and -2 is % d"


(r2))

Output

Random number between 5 and 15 is 10
Random number between -10 and -2 is -2

Generate Random Float numbers in Python

A random.random() method is used to generate random floats between 0.0 to 1.

Syntax: random.random()

Example:

In this code, we are using the

random

function from the ‘

random'

module in Python. It prints a random floating-point number between 0 and 1 when you call

random()

.

Working with Sequences

The application of the Python Random module is not limited to single values such as integer or float as we can use it to work on sequences as well.

Random K Elements From List (Without Replacing)

In case we have a list container and we want to pick only k values from it such that all of them are randomly picked without replacement, we can use sample(l,k) where l is the list container with elements and k is the number of required elements.

Syntax:


import random items = [ 2, 3, 4, 5, 37, 8, 9, 10] print(random.sample(items, 3))

Output:


[37, 9, 5]

Random K Elements From List (With Replacing Items)

In such a scenario where a sequence and k random values need to be picked, replacing the element then choice() function is the alternative to the sample() function where the same element can be picked multiple times. Give Python Random K elements from list code is given below:-

Syntax:


import random items = [2, 3, 4, 25, 7, 38, 9] print(random.choices(items, k=3))

Output:


[2, 3, 3]

Fix Python Relative Imports and Auto-completion in VSCode
Fix Python Relative Imports and Auto-completion in VSCode

Recipes¶

These recipes show how to efficiently make random selections
from the combinatoric iterators in the

itertools

module:

def random_product(*args, repeat=1): “Random selection from itertools.product(*args, **kwds)” pools = [tuple(pool) for pool in args] * repeat return tuple(map(random.choice, pools)) def random_permutation(iterable, r=None): “Random selection from itertools.permutations(iterable, r)” pool = tuple(iterable) r = len(pool) if r is None else r return tuple(random.sample(pool, r)) def random_combination(iterable, r): “Random selection from itertools.combinations(iterable, r)” pool = tuple(iterable) n = len(pool) indices = sorted(random.sample(range(n), r)) return tuple(pool[i] for i in indices) def random_combination_with_replacement(iterable, r): “Choose r elements with replacement. Order the result to match the iterable.” # Result will be in set(itertools.combinations_with_replacement(iterable, r)). pool = tuple(iterable) n = len(pool) indices = sorted(random.choices(range(n), k=r)) return tuple(pool[i] for i in indices)

The default

random()

returns multiples of 2⁻⁵³ in the range
0.0 ≤ x < 1.0. All such numbers are evenly spaced and are exactly
representable as Python floats. However, many other representable
floats in that interval are not possible selections. For example,

0.05954861408025609

isn’t an integer multiple of 2⁻⁵³.

The following recipe takes a different approach. All floats in the interval are possible selections. The mantissa comes from a uniform distribution of integers in the range 2⁵² ≤ mantissa < 2⁵³. The exponent comes from a geometric distribution where exponents smaller than -53 occur half as often as the next larger exponent.

from random import Random from math import ldexp class FullRandom(Random): def random(self): mantissa = 0x10_0000_0000_0000 | self.getrandbits(52) exponent = -53 x = 0 while not x: x = self.getrandbits(32) exponent += x.bit_length() – 32 return ldexp(mantissa, exponent)

All real valued distributions in the class will use the new method:

>>> fr = FullRandom() >>> fr.random() 0.05954861408025609 >>> fr.expovariate(0.25) 8.87925541791544

The recipe is conceptually equivalent to an algorithm that chooses from
all the multiples of 2⁻¹⁰⁷⁴ in the range 0.0 ≤ x < 1.0. All such
numbers are evenly spaced, but most have to be rounded down to the
nearest representable Python float. (The value 2⁻¹⁰⁷⁴ is the smallest
positive unnormalized float and is equal to

math.ulp(0.0)

.)

See also

Generating Pseudo-random Floating-Point Values a
paper by Allen B. Downey describing ways to generate more
fine-grained floats than normally generated by

random()

.

Python Random module generates random numbers in Python. These are pseudo-random numbers means they are not truly random.

This module can be used to perform random actions such as generating random numbers, printing random a value for a list or string, etc. It is an in-built function in Python.

Common Issues and Solutions with randint

While using Python’s

randint()

function, you might encounter certain issues. Let’s discuss some common problems and their solutions.

Forgetting to Import the Random Module

One of the most common mistakes is forgetting to import the random module. Without importing it, Python won’t recognize the

randint()

function, leading to an error.


number = randint(1, 10) print(number) # Output: # NameError: name 'randint' is not defined

In this example, we forgot to import the random module, so Python raises a

NameError

because it doesn’t recognize

randint()

. The solution is to import the random module at the beginning of your code.


import random number = random.randint(1, 10) print(number) # Output: # (A random number between 1 and 10)

By importing the random module with

import random

, we can now use the

randint()

function without any issues.

Using Incorrect Range Values

Another common mistake is using incorrect values for the range. Remember, the first parameter should be less than or equal to the second. If it’s greater, Python will raise a

ValueError

.


import random number = random.randint(10, 1) print(number) # Output: # ValueError: empty range for randrange() (10,1, -9)

In this example, we tried to generate a random number between 10 and 1, which is an empty range. The solution is to ensure the first parameter is less than or equal to the second.

Deploy a Django web app to FL0 [FREE]
Deploy a Django web app to FL0 [FREE]

Python3


import


random


print


(random.random())

Output:
0.059970593824388185

Create a List of Random Numbers

The random() method in Python from the random module generates a float number between 0 and 1. Here, we are using Python Loop and append random numbers in the Python list.

Discrete distributions¶

The following function generates a discrete distribution.

random.binomialvariate(n=1, p=0.5)¶

Binomial distribution. Return the number of successes for n independent trials with the probability of success in each trial being p:

Mathematically equivalent to:

sum(random() < p for i in range(n))

The number of trials n should be a non-negative integer. The probability of success p should be between


0.0 <= p <= 1.0

. The result is an integer in the range

0 <= X <= n

.

New in version 3.12.

random numbers in python
random numbers in python

Wrapping Up: Python’s randint Function

Python’s

randint()

function is a powerful tool in the

random

module, providing a straightforward way to generate random integers within a specified range. From simple applications to more complex scenarios,

randint()

offers a reliable solution for random number generation.

While

randint()

is generally easy to use, common issues include forgetting to import the

random

module and using incorrect range values. These can be easily avoided by following best practices such as always importing necessary modules and ensuring correct parameter values.

Beyond

randint()

, Python offers other methods for random number generation. These include the

random()

and

uniform()

functions in the

random

module, and the

numpy.random.randint()

function in the NumPy module. Each method has its unique advantages and can be more suitable depending on your specific needs.

Random number generation is a fundamental aspect of programming with diverse applications. By mastering Python’s

randint()

function and understanding other random number generation methods, you can harness the power of randomness in your Python projects.

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.

random.random()¶

Return the next random floating point number in the range


0.0 <= X < 1.0

random.uniform(a, b)¶

Return a random floating point number N such that


a <= N <= b

for

a <= b

and

b <= N <= a

for

b < a

.

The end-point value

may or may not be included in the range depending on floating-point rounding in the equation

a + (b-a) * random()

.

random.triangular(low, high, mode)¶

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.betavariate(alpha, beta)¶

Beta distribution. Conditions on the parameters are


alpha > 0

and

beta > 0

. Returned values range between 0 and 1.

random.expovariate(lambd=1.0)¶

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.

Changed in version 3.12: Added the default value for


lambd

.

random.gammavariate(alpha, beta)¶

Gamma distribution. (Not the gamma function!) The shape and scale parameters, alpha and beta, must have positive values. (Calling conventions vary and some sources define ‘beta’ as the inverse of the scale).

The probability distribution function is:

x ** (alpha – 1) * math.exp(-x / beta) pdf(x) = ————————————– math.gamma(alpha) * beta ** alpha

random.gauss(mu=0.0, sigma=1.0)¶

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.

Changed in version 3.11: mu and sigma now have default arguments.

random.lognormvariate(mu, sigma)¶

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.

random.normalvariate(mu=0.0, sigma=1.0)¶

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

Changed in version 3.11: mu and sigma now have default arguments.

random.vonmisesvariate(mu, kappa)¶

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.

random.weibullvariate(alpha, beta)¶

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

Python Random Module Functions - Coding Examples (random, randint, choice, randrange)
Python Random Module Functions – Coding Examples (random, randint, choice, randrange)

Exploring Alternatives to randint

While

randint()

is a powerful tool for generating random integers, Python offers other functions and modules for random number generation. These include the

random()

function, the

uniform()

function, and the NumPy module.

The random Function

The

random()

function is another part of Python’s random module. Unlike

randint()

,

random()

generates a random floating-point number between 0.0 and 1.0.


import random random_number = random.random() print(random_number) # Output: # (A random floating-point number between 0.0 and 1.0)

The

random()

function doesn’t take any arguments and returns a random float in the range [0.0, 1.0).

The uniform Function

The

uniform(a, b)

function generates a random floating-point number between and . It’s similar to

randint()

, but it works with floating-point numbers.


import random random_number = random.uniform(1.0, 10.0) print(random_number) # Output: # (A random floating-point number between 1.0 and 10.0)

In this example,

random.uniform(1.0, 10.0)

generates a random float between 1.0 and 10.0.

The NumPy Module

NumPy, a powerful library for numerical computation in Python, also provides functions for random number generation. For instance,

numpy.random.randint()

generates random integers in a similar way to Python’s

randint()

.


import numpy random_number = numpy.random.randint(1, 10) print(random_number) # Output: # (A random integer between 1 and 10)

In this example,

numpy.random.randint(1, 10)

generates a random integer between 1 and 10, just like Python’s

randint()

function.

These alternative methods offer more flexibility and options for random number generation in Python. Depending on your specific needs, you might find one of these methods more suitable than

randint()

.

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 −

[16, 19, 13, 18, 15]

Kickstart Your Career

Get certified by completing the course

Get Started

We often need to make random selections or generate random values while programming in Python. In this post, I will describe the use of the random module in Python. The random module provides access to functions to generate random numbers and strings. It also provides functions to select random elements from a list or shuffle a list. We will discuss each function one by one.

Why Is \
Why Is \”random.seed()\” So Important In Python?

random.randrange() to generate random integers within a range

Now let’s see how to use the

random.randrange()

function to get a random integer number from the given exclusive range by specifying the increment.

Syntax


random.randrange(start, stop[, step])

This function returns a random integer from a

range(start, stop, step)

. For example,

random.randrange(0, 10, 2)

will generate any random numbers from [0, 2, 4, 6, 8].

Parameters

It takes three parameters. Out of three, two parameters are optional. i.e.,

start

and

step

are optional.


  • start

    : it is the star number in a range. i.e., lower limit. The default value is 0 if not specified.

  • stop

    : It is the end/last number in a range. It is the upper limit.

  • step

    : Specify the increment value in range. The generated random number is divisible by step. The default value is 1 if not specified.

random.randrange() examples

In the following example, we are trying to print a random int in a given range. This example demonstrates all the variants of

random.randrange()

function.


import random # random integer from 0 to 9 num1 = random.randint(0, 9) print(num1) # output 5 # Random integer from 10 to 100 num2 = random.randint(10, 100) print(num2) # Output 84

Note:

  • The

    randrange()

    doesn’t consider the stop number while generating a random integer. It is an exclusive random range. For example,

    randrange(2, 20, 2)

    will return any random number between 2 to 20, such as 2, 4, 6, …18. It will never select 20.
  • Same as

    randint()

    , you cannot use float value in

    randrange()

    too. It will raise a

    ValueError

    (non-integer arg 1 for randrange()) if you use non-integers.

Random number of a specific length

Let’s see how to generate a random number of length n. For example, any random number of length four, such as 7523, 3674. We can accomplish this using both

randint()


randrange()

.


import random # random number of length 4 num1 = random.randint(1000, 9999) # random number of length 4 with step 2 num2 = random.randrange(1000, 10000, 2) print(num1, num2) # Output 3457 5116

Note: As you can see, we set a

start = 1000

and a

stop = 10000

because we want to generate the random number of length 4 (from 1000 to 9999).

Random integer number multiple of n

For example, let’s generate a random number between x and y multiple of 3 like 3, 6, 39, 66.


import random num = random.randrange(3, 300, 3) print(num) # output 144

Shuffle List in Python

A random.shuffle() method is used to shuffle a sequence (list). Shuffling means changing the position of the elements of the sequence. Here, the shuffling operation is inplace.

Syntax: random.shuffle(sequence, function)

Example: Shuffling a List

This code uses the

random.shuffle()

function from the ‘

random

module to shuffle the elements of a list named ‘

sample_list'

. It first prints the original order of the list, then shuffles it twice. The second shuffle creates a new random order, and the list’s content is displayed after each shuffle. This demonstrates how the elements are rearranged randomly in the list with each shuffle operation.

Generating ACTUALLY Random Numbers in Python
Generating ACTUALLY Random Numbers in Python

Shuffling Sequences

To shuffle the list with random ordering, the shuffle() function can be used to perform the operation.

Syntax:


import random # Shuffling Sequences items = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10] random.shuffle(items) print(items)

Output:


[5, 8, 6, 11, 3, 10, 9, 4, 7, 2]

Generate a list of random integer numbers

In this section, we will see how to generate multiple random numbers. Sometimes we need a sample list to perform testing. In this case, instead of creating it manually, we can create a list with random integers using a

randint()

or

randrange()

. In this example, we will see how to create a list of 10 random integers.


import random random_list = [] # Set a length of the list to 10 for i in range(0, 10): # any random numbers from 0 to 1000 random_list.append(random.randint(0, 1000)) print(random_list) # Output [994, 287, 65, 994, 936, 462, 839, 160, 689, 624]

Create a list of random numbers without duplicates

Note: In the above example, there is a chance of occurring a duplicate number in a list.

If you want to make sure each number in the list is unique, use the random.sample() method to generate a list of unique random numbers.

  • The

    sample()

    returns a sampled list of selected random numbers within a range of values.
  • It never repeats the element so that we can get a list of random numbers without duplicates


import random # Generate 10 unique random numbers within a range num_list = random.sample(range(0, 1000), 10) print(num_list) # Output [499, 580, 735, 784, 574, 511, 704, 637, 472, 211]

Note: You can also use the step parameter of the range() function to specify the increment. For example, you want a list of 10 random numbers, but each integer in a list must be divisible by 5, then use

random.sample(range(0, 1000, 5), 10)

Sort random numbers list

Use the

sort()

function to sort a list of random integers in ascending order


import random sample_list = random.sample(range(50, 500, 5), 5) # Before sorting print(sample_list) # Output [305, 240, 260, 235, 445] sample_list.sort() # After sorting print(sample_list) # Output [235, 240, 260, 305, 445]

Python random numbers 🎲
Python random numbers 🎲

Frequently Asked Questions Related to Python Random Module

Here are some FAQs related to Python Random Module.

1. How do I generate a random integer in Python using the “random” module?You can generate a random integer within a specified range using the randint() function. For example, random.randint(1, 10) generates a random integer between 1 and 10, inclusive.

2. Can I set the seed for the random number generator to make my results reproducible?Yes, you can set the seed using the seed() function from the “random” module. Setting the seed ensures that you get the same sequence of random numbers in each run, which can be useful for debugging or creating reproducible results.

3. What’s the difference between random.random() and random.uniform(a, b) for generating random floating-point numbers?Both functions generate random floating-point numbers between 0 and 1. The difference is that random.random() returns a number in the half-open interval [0, 1), while random.uniform(a, b) generates a random number in the closed interval [a, b].

4. How can I randomly shuffle a list in Python?You can shuffle a list using the shuffle() function from the “random” module. For example, random.shuffle(my_list) will shuffle the elements of my_list in place.

5. What’s the difference between pseudo-random and truly random numbers in Python?Python’s “random” module generates pseudo-random numbers, which are determined by an initial seed value. While they appear random for practical purposes, they are not truly random and can be reproduced if the seed is known. To achieve true randomness, you would need to use external hardware or sources of entropy.

  • Trending Categories
  • Data Structure
  • Networking
  • RDBMS
  • Operating System
  • Java
  • MS Excel
  • iOS
  • HTML
  • CSS
  • Android
  • Python
  • C Programming
  • C++
  • C#
  • MongoDB
  • MySQL
  • Javascript
  • PHP
  • Physics
  • Chemistry
  • Biology
  • Mathematics
  • English
  • Economics
  • Psychology
  • Social Studies
  • Fashion Studies
  • Legal Studies
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer’s Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

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.

Python Random random() Syntax

Syntax : random.random()

Parameters : This method does not accept any parameter.

Returns : This method returns a random floating number between 0 and 1.

Python random.random() Method Example

Random in Python generate different number every time you run this program.

How To Generate Random Numbers In Python
How To Generate Random Numbers In Python

Understanding Python’s randint Function

Python’s

randint()

is a function that belongs to the

random

module. It is used to generate a random integer within a defined range. The function takes two parameters: the start and end of the range, inclusive.

Using randint: A Simple Example

Let’s look at a simple code example to understand how

randint()

works:


import random number = random.randint(1, 10) print(number) # Output: # (A random number between 1 and 10)

In this example,

import random

is used to import the random module, which contains the randint function. Next,

random.randint(1, 10)

is used to generate a random integer between 1 and 10, inclusive. The result is then stored in the variable

number

, which is printed out.

Parameters and Return Value

The

randint(a, b)

function takes two parameters:

  • : The lower limit of the range (inclusive).
  • : The upper limit of the range (inclusive).

The function returns a random integer such that

a <= N <= b

.

Understanding the Output

The output of the

randint()

function is a random integer within the specified range. In our example, the output is a random number between 1 and 10. Each time you run the code, you might get a different number because the selection is random.

By understanding the basics of Python’s

randint()

function, you can start to harness the power of random number generation in your coding projects.

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.

Almost all module functions depend on the basic function

random()

, which
generates a random float uniformly in the half-open range

0.0 <= X < 1.0

.
Python uses the Mersenne Twister as the core generator. It produces 53-bit precision
floats and has a period of 2**19937-1. The underlying implementation in C is
both fast and threadsafe. The Mersenne Twister is one of the most extensively
tested random number generators in existence. However, being completely
deterministic, it is not suitable for all purposes, and is completely unsuitable
for cryptographic purposes.

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.

Class

Random

can also be subclassed if you want to use a different
basic generator of your own devising: see the documentation on that class for
more details.

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.

Warning

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

secrets

module.

See also

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.

Python 3 - Generating and Scaling Random Numbers
Python 3 – Generating and Scaling Random Numbers

Functions for sequences¶

random.choice(seq)¶

Return a random element from the non-empty sequence seq. If seq is empty, raises


IndexError

.

random.choices(population, weights=None, *, cum_weights=None, k=1)¶

Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises


IndexError

.

If a weights sequence is specified, selections are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights (perhaps computed using


itertools.accumulate()

). For example, the relative weights

[10, 5, 30, 5]

are equivalent to the cumulative weights

[10, 15, 45, 50]

. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.

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.

For a given seed, the


choices()

function with equal weighting typically produces a different sequence than repeated calls to

choice()

. The algorithm used by

choices()

uses floating point arithmetic for internal consistency and speed. The algorithm used by

choice()

defaults to integer arithmetic with repeated selections to avoid small biases from round-off error.

New in version 3.6.

Changed in version 3.9: Raises a


ValueError

if all weights are zero.

random.shuffle(x)¶

Shuffle the sequence x in place.

To shuffle an immutable sequence and return a new shuffled list, use


sample(x, k=len(x))

instead.

Note that even for small


len(x)

, the total number of permutations of x can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.

Changed in version 3.11: Removed the optional parameter random.

random.sample(population, k, *, counts=None)¶

Return a k length list of unique elements chosen from the population sequence. 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.

Repeated elements can be specified one at a time or with the optional keyword-only counts parameter. For example,


sample(['red', 'blue'], counts=[4, 2], k=5)

is equivalent to

sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)

.

To choose a sample from a range of integers, use a


range()

object as an argument. This is especially fast and space efficient for sampling from a large population:

sample(range(10000000), k=60)

.

If the sample size is larger than the population size, a


ValueError

is raised.

Changed in version 3.9: Added the counts parameter.

Changed in version 3.11: The population must be a sequence. Automatic conversion of sets to lists is no longer supported.

Frequently Asked Questions Related to Python Random Module

Here are some FAQs related to Python Random Module.

1. How do I generate a random integer in Python using the “random” module?You can generate a random integer within a specified range using the randint() function. For example, random.randint(1, 10) generates a random integer between 1 and 10, inclusive.

2. Can I set the seed for the random number generator to make my results reproducible?Yes, you can set the seed using the seed() function from the “random” module. Setting the seed ensures that you get the same sequence of random numbers in each run, which can be useful for debugging or creating reproducible results.

3. What’s the difference between random.random() and random.uniform(a, b) for generating random floating-point numbers?Both functions generate random floating-point numbers between 0 and 1. The difference is that random.random() returns a number in the half-open interval [0, 1), while random.uniform(a, b) generates a random number in the closed interval [a, b].

4. How can I randomly shuffle a list in Python?You can shuffle a list using the shuffle() function from the “random” module. For example, random.shuffle(my_list) will shuffle the elements of my_list in place.

5. What’s the difference between pseudo-random and truly random numbers in Python?Python’s “random” module generates pseudo-random numbers, which are determined by an initial seed value. While they appear random for practical purposes, they are not truly random and can be reproduced if the seed is known. To achieve true randomness, you would need to use external hardware or sources of entropy.

Using Python’s randint for Random Number Generation

Python’s randint function is a powerful tool in your coding arsenal. It’s like a digital dice, capable of generating random numbers for a variety of applications.

This function can seem a bit confusing at first, but fear not! In this guide, we will dive deep into the ins and outs of using randint in Python. By the end of this guide, you will be able to confidently use the randint function in your own Python projects.

So, let’s roll the dice and start our journey into the world of Python’s randint function.

How to randomly select 3 elements of a list in python
How to randomly select 3 elements of a list in python

Conclusion

In this article, we have discussed different functions in the random module in Python. We have also discussed a code example using the

choice()

function to simulate coin flips.

To learn more about Python programming, you can read this article on list comprehension in Python. You might also like this article on string manipulation.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Shuffling Sequences

To shuffle the list with random ordering, the shuffle() function can be used to perform the operation.

Syntax:


import random # Shuffling Sequences items = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10] random.shuffle(items) print(items)

Output:


[5, 8, 6, 11, 3, 10, 9, 4, 7, 2]

How the \
How the \”Import Random\” Library in Python Works

Functions for integers¶

random.randrange(stop)¶
random.randrange(start, stop[, step])

Return a randomly selected element from


range(start, stop, step)

.

This is roughly equivalent to


choice(range(start, stop, step))

but supports arbitrarily large ranges and is optimized for common cases.

The positional argument pattern matches the


range()

function.

Keyword arguments should not be used because they can be interpreted in unexpected ways. For example


randrange(start=100)

is interpreted as

randrange(0, 100, 1)

.

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.

Changed in version 3.12: Automatic conversion of non-integer types is no longer supported. Calls such as


randrange(10.0)

and

randrange(Fraction(10, 1))

now raise a

TypeError

.

random.randint(a, b)¶

Return a random integer N such that


a <= N <= b

. Alias for

randrange(a, b+1)

.

random.getrandbits(k)¶

Returns a non-negative Python integer with k random bits. This method is supplied with the Mersenne Twister 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.

Python3


from


random


import


random


lst


[]


for


in


range


10


):


lst.append(random())


print


(lst)

Output:

[0.12144204979175777, 0.27614050014306335, 0.8217122381411321, 0.34259785168486445, 0.6119383347065234, 0.8527573184278889, 0.9741465121560601, 0.21663626227016142, 0.9381166706029976, 0.2785298315133211]

Python Random seed() Method

This function generates a random number based on the seed value. It is used to initialize the base value of the pseudorandom number generator. If the seed value is 10, it will always generate 0.5714025946899135 as the first random number.

Python RANDOM Number Generator Module Tutorial
Python RANDOM Number Generator Module Tutorial

Python3


import


random


list1


print


(random.choice(list1))

Example 2: Creating random numbers with Python seed() in Python.

As stated above random module creates pseudo-random numbers. Random numbers depend on the seeding value. For example, if the seeding value is 5 then the output of the below program will always be the same. Therefore, it must not be used for encryption.

The code sets the random number generator’s seed to 5 using

random.seed(5)

, ensuring reproducibility. It then prints two random floating-point numbers between 0 and 1 using

random.random()

. The seed makes these numbers the same every time you run the code with a seed of 5, providing consistency in the generated random values.

Real-World Applications of Python’s randint

Python’s

randint()

function isn’t just for academic exercises—it has practical applications in real-world scenarios. Let’s explore some of these applications.

Simulations

In simulations,

randint()

can be used to generate random inputs. For example, in a weather simulation,

randint()

could generate random temperatures or wind speeds.


import random random_temperature = random.randint(-10, 40) print('Random Temperature:', random_temperature, '°C') # Output: # Random Temperature: (A random number between -10 and 40) °C

In this code, we’re using

randint()

to generate a random temperature between -10 and 40 degrees Celsius.

Games

In games,

randint()

can be used to create unpredictable elements, making the game more exciting. For instance, in a dice game,

randint()

could be used to generate the dice roll.


import random dice_roll = random.randint(1, 6) print('Dice Roll:', dice_roll) # Output: # Dice Roll: (A random number between 1 and 6)

In this code, we’re using

randint()

to simulate a dice roll, generating a random number between 1 and 6.

Data Analysis

In data analysis,

randint()

can be used to generate random samples from a larger dataset. This can ensure a more representative sample and more accurate analysis.

P_33  Random Module in Python | Python Tutorials for Beginners
P_33 Random Module in Python | Python Tutorials for Beginners

What is a Python Random Module?

Random module comes built-in with python which means that we do not need to install a package but just import and use it on the go. Python Random Module is useful in implementing a randomization algorithm. It can be used for generating integers from a specified range to pick the number from. Also, we have the feature to choose from a sequence of numbers of choice we can pick from a list of elements.

However, it generates the numbers in a pseudorandom manner that is not completely random if we deep dive further into its working mechanism under the hood but still remains effective for usage. Different functions from the Python Random Module are going to be discussed in this article with examples and explanations for each.

Seeding can be performed using seed() function where on seeding, the same value will be generated. It is used as a tool to initialize the value generator to reset in an algorithmic manner that once seeded, the sequence of values obtained remains the same.

Given below is an example of seeding in Python Random Module.

Example of Python Random Module:

import random # Seed the random number generator random.seed(2) # Generate 4 random numbers for i in range(4): print(random.random()) random.seed(2)

Output:


0.9560342718892494 0.9560342718892494 0.9560342718892494 0.9560342718892494

Python3


from


random


import


random


print


(random())

Randomly Select Elements from a List in Python

Random sampling from a list in Python (random.choice, and sample)

Example 1: Python random.choice() function is used to return a random item from a list, tuple, or string.

The code uses the

random.choice()

function from the

random

module to randomly select elements from different data types. It demonstrates selecting a random element from a list, a string, and a tuple. The chosen elements will vary each time you run the code, making it useful for random selection from various data structures.

Modules In Python : The Random Module
Modules In Python : The Random Module

Generating Random Strings

The Python Random module is helpful in generating random strings of certain length provided as input by the user. The strings can be of different bases depending upon the function with code below where a hexadecimal string of length 10 is generated and 10 is encoded into base64 and a string value is returned.

Syntax:-


import random # Generating Random Strings print(random.hex(10)) print(random.b64encode(10))

Output:


'8b7c11d1f2' b'Lp0RRmV7tg=='

Alternative Generator¶

class random.Random([seed])¶

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


random

module.

Changed in version 3.11: Formerly the seed could be any hashable object. Now it is limited to:


None

,

int

,

float

,

str

,

bytes

, or

bytearray

.

Subclasses of


Random

should override the following methods if they wish to make use of a different basic generator:

seed(a=None, version=2)¶

Override this method in subclasses to customise the


seed()

behaviour of

Random

instances.

getstate()¶

Override this method in subclasses to customise the


getstate()

behaviour of

Random

instances.

setstate(state)¶

Override this method in subclasses to customise the


setstate()

behaviour of

Random

instances.

random()¶

Override this method in subclasses to customise the


random()

behaviour of

Random

instances.

Optionally, a custom generator subclass can also supply the following method:

getrandbits(k)¶

Override this method in subclasses to customise the


getrandbits()

behaviour of

Random

instances.

class random.SystemRandom([seed])¶

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.

What are Random Modules in Python - Explained with Examples  | Python Tutorial
What are Random Modules in Python – Explained with Examples | Python Tutorial

Understanding Random Number Generation in Python

Random number generation is a fundamental concept in programming that has a variety of applications, from game development to data analysis. Python’s

random

module, which includes the

randint()

function, is a powerful tool for generating these random numbers.

The Role of Python’s Random Module

Python’s

random

module provides a suite of functions for generating random numbers. These functions include

randint()

,

random()

,

uniform()

, and many others. Each function generates a random number in a different way or within a different range.


import random random_integer = random.randint(1, 10) random_float = random.random() random_uniform = random.uniform(1.0, 10.0) print(random_integer, random_float, random_uniform) # Output: # (A random integer between 1 and 10, a random float between 0.0 and 1.0, a random float between 1.0 and 10.0)

In this code, we’re using three functions from Python’s

random

module to generate different types of random numbers. Each function provides a unique way to generate random numbers, making the

random

module a versatile tool for random number generation in Python.

The Importance of Randomness in Programming

Randomness plays a crucial role in many areas of programming. For instance, in game development, randomness can be used to create unpredictable gameplay elements. In data analysis, random sampling can help ensure a representative sample of data. By understanding how to generate random numbers in Python, you can harness the power of randomness in your own programming projects.

Generating Random Strings

The Python Random module is helpful in generating random strings of certain length provided as input by the user. The strings can be of different bases depending upon the function with code below where a hexadecimal string of length 10 is generated and 10 is encoded into base64 and a string value is returned.

Syntax:-


import random # Generating Random Strings print(random.hex(10)) print(random.b64encode(10))

Output:


'8b7c11d1f2' b'Lp0RRmV7tg=='

Points to remember about randint() and randrange()

  • Use

    randint()

    when you want to generate a random number from an inclusive range.
  • Use

    randrange()

    when you want to generate a random number within a range by specifying the increment. It produces a random number from an exclusive range.

You should be aware of some value constraints of a

randrange()

function.

  • The

    randint(

    ) rand

    randrange()

    works only with integers. You cannot use float numbers.
  • The step must not be 0. If it is set to 0, you will get a

    ValueError: zero step for randrange()
  • The start should not be greater than stop if you are using all positive numbers. If you set start greater than stop, you will get a ValueError: empty range for randrange()

Examples


import random # ValueError: empty range for randrange() print(random.randrange(100, 10, 2))

But, you can also set a start value greater than stop if you are using a negative step value.


import random print(random.randrange(100, 10, -2)) # output 60

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

There are certain situations that involve games or simulations which work on a non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications:

  • Creating pseudo-random numbers on Lottery scratch cards
  • reCAPTCHA on login forms uses a random number generator to define different numbers and images
  • Picking a number, flipping a coin, and throwing of a dice related games required random numbers
  • Shuffling deck of playing cards

In Python, random numbers are not generated implicitly; therefore, it provides a random module in order to generate random numbers explicitly. A random module in Python is used to create random numbers. To generate a random number, we need to import a random module in our program using the command:

import random

Python3


import


random


sample_list


print


"Original list : "


print


(sample_list)


random.shuffle(sample_list)


print


"\nAfter the first shuffle : "


print


(sample_list)


random.shuffle(sample_list)


print


"\nAfter the second shuffle : "


print


(sample_list)

Output

Original list :
[1, 2, 3, 4, 5]
After the first shuffle :
[3, 2, 1, 5, 4]
After the second shuffle :
[2, 3, 1, 5, 4]

In this article we discussed about Python Random module, and also saw some examples of functions in random module in Python. Random module in Python is very important and contains very useful functions.

Hope this helps you in using Python Random module functions.

More on Python Modules:

Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated :
20 Dec, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Python Random Module

Python has a built-in module that you can use to make random numbers.

The

random

module has a set of methods:

Method Description
seed() Initialize the random number generator
getstate() Returns the current internal state of the random number generator
setstate() Restores the internal state of the random number generator
getrandbits() Returns a number representing the random bits
randrange() Returns a random number between the given range
randint() Returns a random number between the given range
choice() Returns a random element from the given sequence
choices() Returns a list with a random selection from the given sequence
shuffle() Takes a sequence and returns the sequence in a random order
sample() Returns a given sample of a sequence
random() Returns a random float number between 0 and 1
uniform() Returns a random float number between two given parameters
triangular() Returns a random float number between two given parameters, you can also set a mode parameter to specify the midpoint between the two other parameters
betavariate() Returns a random float number between 0 and 1 based on the Beta distribution (used in statistics)
expovariate() Returns a random float number based on the Exponential distribution (used in statistics)
gammavariate() Returns a random float number based on the Gamma distribution (used in statistics)
gauss() Returns a random float number based on the Gaussian distribution (used in probability theories)
lognormvariate() Returns a random float number based on a log-normal distribution (used in probability theories)
normalvariate() Returns a random float number based on the normal distribution (used in probability theories)
vonmisesvariate() Returns a random float number based on the von Mises distribution (used in directional statistics)
paretovariate() Returns a random float number based on the Pareto distribution (used in probability theories)
weibullvariate() Returns a random float number based on the Weibull distribution (used in statistics)

I’m having problems with Python’s import random function. It seems that

import random

and

from random import random

are importing different things. I am currently using Python 2.7.3


Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> random() Traceback (most recent call last): File " ", line 1, in

random() NameError: name 'random' is not defined >>> random.randint(1,5) Traceback (most recent call last): File " ", line 1, in

random.randint(1,5) NameError: name 'random' is not defined >>> import random >>> random() Traceback (most recent call last): File " ", line 1, in

random() TypeError: 'module' object is not callable >>> random.randint(1,5) 2 >>> from random import random >>> random() 0.28242411635200193 >>> random.randint(1,5) Traceback (most recent call last): File " ", line 1, in

random.randint(1,5) AttributeError: 'builtin_function_or_method' object has no attribute 'randint' >>>

In this lesson, we will see how to use the

randrange()

and

randint()

functions of a Python random module to generate a random integer number.

Using

randrange()

and

randint()

functions of a random module, we can generate a random integer within a range. In this lesson, you’ll learn the following functions to generate random numbers in Python. We will see each one of them with examples.

Function Description
Returns any random integer from 0 to 9
Returns a random integer from 0 to 19
Returns a random integer from 2 to 19.
Returns any random integer from 100 to 999 with step 3. For example, any number from 100, 103, 106 … 994, 997.
Returns a random negative integer between -50 to -6.
Returns a list of random numbers
Returns a secure random number

Expanding the Range of randint

Python’s

randint()

function isn’t limited to small ranges. In fact, you can generate random integers in any range you like. For example, if you’re simulating a lottery draw, you might need to generate numbers between 1 and 1000:


import random lottery_number = random.randint(1, 1000) print(lottery_number) # Output: # (A random number between 1 and 1000)

In this example, we’ve expanded the range of

randint()

to generate a random number between 1 and 1000. This demonstrates the flexibility of the

randint()

function.

Keywords searched by users: import random python 3

Random Module-Python
Random Module-Python
Python Random.Randint() With Examples - Spark By {Examples}
Python Random.Randint() With Examples – Spark By {Examples}
Python Random Randrange() - Javatpoint
Python Random Randrange() – Javatpoint
How To Generate A Random Number In Python | Python Central
How To Generate A Random Number In Python | Python Central
Python 3 Quick Code: Get A Random Item From A List With An Even Chance Of  Being Chosen | Delightly Linux
Python 3 Quick Code: Get A Random Item From A List With An Even Chance Of Being Chosen | Delightly Linux
Python Random Randrange() - Javatpoint
Python Random Randrange() – Javatpoint
Python Random.Randint() With Examples - Spark By {Examples}
Python Random.Randint() With Examples – Spark By {Examples}
Random Module In Python | Complete Guide To Random Module In Python
Random Module In Python | Complete Guide To Random Module In Python
The Randint() Method In Python | Digitalocean
The Randint() Method In Python | Digitalocean
How To Write A Python Program For Generating A List Of Random Numbers That  Vary From 100 To 999 Without Repetition - Quora
How To Write A Python Program For Generating A List Of Random Numbers That Vary From 100 To 999 Without Repetition – Quora
Random Number Generator In Python | Examples Of Random Number
Random Number Generator In Python | Examples Of Random Number
How To Import Random Module In Python@Computerexcelsolution - Youtube
How To Import Random Module In Python@Computerexcelsolution – Youtube
Python Program# Import The Random Module Import Random Def Ra.Pdf
Python Program# Import The Random Module Import Random Def Ra.Pdf
Solved 1. What Will Be The Output Of The Following Python | Chegg.Com
Solved 1. What Will Be The Output Of The Following Python | Chegg.Com
Random Number Generator In Python | Examples Of Random Number
Random Number Generator In Python | Examples Of Random Number
Python Turtle - Picking A Random Number - Youtube
Python Turtle – Picking A Random Number – Youtube
Python Shuffle List: Random, Shuffle, Sample Explained | Master Data Skills  + Ai
Python Shuffle List: Random, Shuffle, Sample Explained | Master Data Skills + Ai
How To Generate 10 Digit Random Number In Python? - Python Guides
How To Generate 10 Digit Random Number In Python? – Python Guides
Solved The Python Random Module Has Functions That Can Be | Chegg.Com
Solved The Python Random Module Has Functions That Can Be | Chegg.Com
Random Number Generator In Python | Examples Of Random Number
Random Number Generator In Python | Examples Of Random Number
Nameerror: Name 'Random' Is Not Defined In Python [Solved] | Bobbyhadz
Nameerror: Name ‘Random’ Is Not Defined In Python [Solved] | Bobbyhadz
Random Module-Python
Random Module-Python

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *