What is random.sample() method in Python?

0 votes
I want to know what is the use of random.sample() in Python. What does this function return? Any help will be appreciated.
Aug 5, 2019 in Python by Arvind
• 2,980 points

2 answers to this question.

0 votes

sample() is an inbuilt function of random module in Python that returns a particular length list of items chosen from the sequence i.e. list, tuple, string or set. Used for random sampling without replacement.

Syntax : random.sample(sequence, k)

sequence: Can be a list, tuple, string, or set.
k: An Integer value, it specify the length of a sample.

Returns: k length new list of elements chosen from the sequence.

For example,

>>> import random
>>> c = list(range(0, 10))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.sample(c, 3)
[3, 1, 0]
answered Aug 5, 2019 by Neel
• 3,010 points
0 votes

The use of random.sample()

  • Randomly select multiple items from any sequence such as a list.
  • Generate the sample of random integers in Python

Most commonly we use random.sample() to randomly pick more than one element from the list without repeating elements

For example, you want to pick 3 random employees from the employee list


import random

employees = ["Ault", "Jhon", "Scoot", "Eric", "Thomas", "Ela"]
sampleList = random.sample(employees, 3)


['Scoot', 'Thomas', 'Eric']

Reference: random.sample()

answered Mar 13 by Vishal
• 180 points

Related Questions In Python

+6 votes
6 answers

What exactly is the function of random.seed() in python?

The seed method is used to initialize the ...READ MORE

answered Oct 29, 2018 in Python by Rahul
0 votes
1 answer

What is a “method” in Python?

It's a function which is a member ...READ MORE

answered Oct 23, 2018 in Python by SDeb
• 13,250 points
0 votes
2 answers

what is a class method in python?

Class Method  class method is the method which is ...READ MORE

answered Apr 8, 2019 in Python by MrBoot
• 1,270 points
0 votes
1 answer

.join() method is used for what purpose in Python?

join() method is used to concatenate or ...READ MORE

answered May 14, 2019 in Python by Taj
• 1,060 points
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,352 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,800 points
0 votes
1 answer

What is setup.py in Python?

Suppose you want to install a module ...READ MORE

answered Jul 10, 2019 in Python by Neel
• 3,010 points
0 votes
1 answer

What is the procedure to install python packages in IPython?

You can use the '!' prefix like ...READ MORE

answered Aug 21, 2019 in Python by Neel
• 3,010 points