Python Program to Generate Random Numbers from 1 to 20 and Append Them to the List

This is a Python Program to generate random numbers from 1 to 20 and append them to the list.

Problem Description

The program takes in the number of elements and generates random numbers from 1 to 20 and appends them to the list.

Problem Solution

1. Import the random module into the program.
2. Take the number of elements from the user.
3. Use a for loop, random.randint() is used to generate random numbers which are them appending to a list.
4. Then print the randomised list.
4. Exit.

Program/Source Code

Here is source code of the Python Program to generate random numbers from 1 to 20 and append them to the list. The program output is also shown below.

import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
    a.append(random.randint(1,20))
print('Randomised list is: ',a)
Program Explanation

1. The random module is imported into the program.
2. User must enter the number of elements from the user.
3. Using a for loop, random.randint() is used to generate random numbers which are then appended to a list.
4. The arguments given inside the random.randint() function are used to specify the range to print the randomized numbers within.
5. Then the randomized list is printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Enter number of elements:3
('Randomised list is: ', [17, 4, 9])
 
Case 2:
Enter number of elements:7
('Randomised list is: ', [16, 5, 18, 19, 6, 7, 20])

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.