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
148 views

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)

Parameters:
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

Example:

import random

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

Output:

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

Reference: random.sample()

answered Mar 13 by Vishal
• 180 points

Related Questions In Python

+4 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
61,046 views
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,230 points
44 views
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
91 views
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
87 views
0 votes
1 answer
+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 777 views
0 votes
0 answers
+4 votes
6 answers
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
109 views
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
36 views