Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Random - random() Function
Next article icon

random.sample() function – Python

Last Updated : 29 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

sample() is an built-in 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. Example:

Python
from random import sample  a = [1, 2, 3, 4, 5]  print(sample(a,3)) 

Output
[2, 5, 1] 

Explanation: This code uses the sample() method to randomly select 3 unique elements from the list a = [1, 2, 3, 4, 5]. The selected elements are printed as a new list.

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.

Examples of random.sample() function

Example 1: Basic use of sample() function

The code demonstrates how to use random.sample() with different types of sequences:

Python
import random  a = [1, 2, 3, 4, 5, 6]  print("With list:", random.sample(a, 3))  s = "GeeksforGeeks" print("With string:", random.sample(s, 4))  t = ("ankit", "geeks", "computer", "science", "portal", "scientist", "btech") print("With tuple:", random.sample(t, 4))  b = {"a", "b", "c", "d", "e"} print("With set:", random.sample(list(b), 3)) 

Output
With list: [3, 4, 5] With string: ['r', 'k', 'f', 'e'] With tuple: ['btech', 'scientist', 'portal', 'science'] With set: ['b', 'a', 'e'] 

Explanation:

  • List: It randomly selects 3 elements from the list a.
  • String: It randomly selects 4 characters from the string s.
  • Tuple: It randomly selects 4 elements from the tuple t.
  • Set: Since random.sample() does not directly work with sets, the set b is converted into a list, and 3 random elements are selected.

Example 2: Sampling More Elements Than Available in List

This code demonstrates the behavior of random.sample() when we try to sample more elements than are present in the list, which will result in a ValueError.

Python
import random  a = [1, 2, 3, 4]  print(random.sample(a, 5))  

Output:

Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 4, in <module>
print(random.sample(a, 5))
~~~~~~~~~~~~~^^^^^^
File "/usr/local/lib/python3.13/random.py", line 434, in sample
raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative

Next Article
Python Random - random() Function
author
ankthon
Improve
Article Tags :
  • Python
  • Python-Built-in-functions
  • python-modules
Practice Tags :
  • python

Similar Reads

  • Python Random Module
    Python Random module generates random numbers in Python. These are pseudo-random numbers means they are not truly random. This module can be used to perform random actions such as generating random numbers, printing random a value for a list or string, etc. It is an in-built function in Python. Appl
    7 min read
  • Python - random.seed( ) method
    random.seed() method in Python is used to initialize the random number generator, ensuring the same random numbers on every run. By default, Python generates different numbers each time, but using .seed() allows result reproducibility. It's most commonly used in: Machine Learning- to ensure model co
    4 min read
  • random.getstate() in Python
    random() module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. random.getstate() The getstate() method of the random module returns an object with the curr
    1 min read
  • random.setstate() in Python
    Random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. random.setstate() The setstate() method of the random module is used in conjugation with the g
    2 min read
  • random.getrandbits() in Python
    random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. random.getrandbits() The getrandbits() method of the random module is used to return an intege
    1 min read
  • randrange() in Python
    The randrange() function in Python's random module is used to generate a random number within a specified range. It allows defining a start, stop, and an optional step value to control the selection of numbers. Unlike randint(), which includes the upper limit, randrange() excludes the stop value. Ex
    4 min read
  • randint() Function in Python
    randint() is an inbuilt function of the random module in Python3. The random module gives access to various useful functions one of them being able to generate random numbers, which is randint(). In this article, we will learn about randint in Python. Python randint() Method SyntaxSyntax: randint(st
    6 min read
  • Python Numbers | choice() function
    choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to im
    1 min read
  • Python - random.choices() method
    The choices() method returns multiple random elements from the list with replacement. Unlike random.choice(), which selects a single item, random.choices() allows us to select multiple items making it particularly useful for tasks like sampling from a population or generating random data. Example: [
    3 min read
  • random.sample() function - Python
    sample() is an built-in 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. Example: [GFGTABS] Python from random import sample a = [1, 2, 3, 4, 5] print(sample(a,3)
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences