How to Auto-generate a list with random elements in Python?

In this article, we are going to learn how to auto-generate a list with random elements in Python with example.

Here we come across the task of generating a list all with random elements.

Python program to Auto-generate a list with random elements

First, in order to auto-generate a list with random numbers, we need to import random packages from the Python standard library as well as a function defined in the random package.

import random

Using ‘import random’ imports the package where we can use any function from the random package.

To auto-generate a list with random elements in Python, we have two methods.

Method 1:Using randrange()

The randrange() is used to perform the task of generating a list with random numbers in a range.

The syntax of randrange():

random.randrange(start,stop,step)

where random is the package.

The randrange() has three parameters:

start argument is the starting element, stop argument is the last element and step is the difference between each number in the sequence.

import random
ls=[random.randrange(0, 100) for i in range(10)]
print("list is : "+str(ls))

output:

list is : [40, 50, 98, 41, 29, 0, 91, 62, 86, 7]

Method 2:Using sample()

sample() is a function of the random package in Python that returns a particular length list of items chosen from the sequence i.e., list.

syntax of sample():

random.sample(sequence,k)

where the sequence can be a list, tuple, string or set and k specifies the list length.

This function returns a new list containing k length elements.

import random
ls=random.sample(range(0,100),10)
print("list is : "+str(ls))

output:

list is : [55, 65, 78, 42, 9, 86, 68, 16, 91, 49]

where range() is a function in Python which returns the sequence of integers to the stop integer, which is generally used to iterate over with for loop.

Also, read: Get n Random items from a List in Python

 

Leave a Reply

Your email address will not be published. Required fields are marked *