Open In App

Python - Random Numbers Summation

Last Updated : 12 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We need to do summation of random numbers. For example, n = [random.randint(1, 10) for _ in range(5)] it will generate random numbers [4, 8, 9, 4, 6] between 1 to 10 so the resultant output should be 29.

Using random.randint()

random.randint(a, b) function generates a random integer between a and b (inclusive). It can be used with sum() and list comprehension to generate multiple random numbers and compute their total sum efficiently.

Python
import random  

# Generate a list of 5 random integers between 1 and 10
n = [random.randint(1, 10) for _ in range(5)]

# Compute the sum of the generated numbers
res = sum(n)

print(n, "Sum:", res)

Output
[5, 4, 8, 7, 5] Sum: 29

Explanation:

  • List comprehension with random.randint(1, 10) generates a list of 5 random integers in the range 1 to 10.
  • Sum(n) function calculates total sum of randomly generated numbers and prints result.

Using random.sample()

random.sample(population, k) function selects k unique random elements from the given population. It can be used to generate a list of random numbers and compute their sum efficiently.

Python
import random  
# Generate a list of 5 unique random numbers from the range 1 to 20
n = random.sample(range(1, 20), 5)

# Compute the sum of the selected numbers
res = sum(n)
print(n, "Sum:", res)

Output
[10, 2, 17, 7, 19] Sum: 55

Explanation:

  • random.sample(range(1, 20), 5) selects 5 unique random numbers from range 1 to 19 without repetition.
  • sum(n) function computes total sum of these randomly chosen unique numbers.

Using random.choices()

random.choices(population, k) function selects k random elements from the given population with replacement meaning duplicates can occur. It can be used to generate a list of random numbers and compute their sum efficiently.

Python
import random 

# Generate a list of 5 random numbers from 1 to 20 (allows duplicates)
n = random.choices(range(1, 20), k=5)

# Compute the sum of the selected numbers
res = sum(n)
print(n, "Sum:", res)

Output
[2, 1, 10, 5, 8] Sum: 26

Explanation:

  • random.choices(range(1, 20), k=5) selects 5 random numbers from 1 to 19 with replacement meaning duplicates may appear.
  • sum(n) function computes the total sum of these randomly chosen numbers.

Next Article
Practice Tags :

Similar Reads