etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Python random choice

In this post, you will learn about the Python random() function.

There is an in-built random module in Python that's used to generate the pseudo-random variables. We can use this to perform some activity randomly, for example, to get a random number, choose an irregular element from a list, randomly shuffle elements, and so on. This module provides several functions to perform operations randomly. In this article, we will learn how to select an element randomly.





Python random.choice

The random.choice() method of the Python random module returns a random element from the given sequence.

Syntax of random.choice()

random.choice(sequence)

Here, the sequence can be any list, string, tuple, or any other kind of sequence. It returns a single item from the sequence. It is a required parameter. It will raise an error IndexError, in case we pass an empty list to the random.choice() function.





Example of random.choice()

Here, we have mentioned few examples of random.choice() method.

import random

x = "ETUTORIALSPOINT"

print("Random from x is: ",random.choice(x))

y = "LAPTOP"

print("Random item y is: ",random.choice(y))
Output of the above code-
Random from x is:  T
Random item y is:  O




Python random choice from list

In the given program, we are using a random random.choice() to select a random value from a list.

import random

num_list= [232, 531, 903, 234, 120, 129, 121]
print("Random item from list is: ", random.choice(num_list))
Output of the above code-
Random item from list is:  234




Python multiple random choices from list

The choices() method of Python returns multiple random elements from the list with replacement. It was introduced in Python version 3.6. It has the following syntax-

random.choices(sequence, weights=None, *, cum_weights=None, k=1)
  • sequence: The sequence can be a list, tuple, or string.
  • weights: It is an optional parameter which is used to weigh the possibility of each value.
  • cum_weights: It is an optional parameter which is used to weigh the possibility for each value, but in this the possibility is accumulated.
  • k: It is an optional parameter that is used to define the length of the returned list.

In the given Python program, we are using the random.choices() function to select multiple random values from a list.

import random

num_list= [232, 531, 903, 234, 120, 129, 121]
print("Random items from list: ", random.choices(num_list, k=3))
Output of the above code-
Random items from list:  [121, 120, 121]




Python multiple random choices from list without repetition

In the above example, you have seen that we got a few repeated numbers as the choices() function can repeat elements. The random module of Python provides a sample() function for random sampling, randomly picking more than one element from the list without repeating elements. The following example demonstrates this.

from random import sample

num_list= [232, 531, 903, 234, 120, 129, 121]
print("Random items from list: ", sample(num_list,3))
Output of the above code-
Random items from list:  [121, 531, 232]




Python random choice from a set

A set is one of the built-in data types in Python used to store multiple items in a single variable. A set is created by using the built-in set() function, placing all the items inside the curly braces {}, separated by commas.

To select a random item from a set, first, copy it into a tuple and then pass the tuple to the choice() function.

import random

x_set = {60, 64, 23, 87, 39}

item = random.choice(tuple(x_set))
# random item from set
print("Random item from set: ", item)
Output of the above code-
Random item from set:  64


Python random choice from a tuple

A tuple is a sequence. Python tuples work exactly like a list, except tuples are immutable, which means they cannot be changed in place. The tuples are written inside parentheses. In the given program, we use the choice() method to select a random item from a tuple.

import random

tup = (25, 15, 63, 90)

# Random choice from a tuple
result = random.choice(tup)
print("Random item from tuple: ", result)
Output of the above code-
Random item from tuple:  63




Python random choice from a dictionary

Python has an in-built dictionary called dict, which we can use to create an arbitrary definition of the character string. A dictionary is a collection, whose values are accessible by key. In the given program, we use the choice() function to select random key-value pairs from a Python dictionary. As, the choice() method doesn't directly work on dictionary, we need to convert a dictionary (dict) into a list and then pass it to the choice() method.

import random

x_dict ={
    'Yellow': 'Marigold', 
    'Red': 'Rose', 
    'White': 'Lilly'}
    
# getting random key
x_list = random.choice(list(x_dict))

print("Random key-value pair- ", x_list, ":", x_dict[x_list])
Output of the above code:
Random key-value pair-  White : Lilly




Related Articles

Sort dictionary by value Python
Add key value pair to dictionary Python
Python program to sum all the items in a dictionary
Convert dictionary to dataframe Python
Convert list to dictionary Python
range and xrange in Python
How to insert values in 2d array in python
splitlines in python
Make a simple calculator in Python
strip function in Python
casefold in Python
Prime factors of a number in Python
Python nonlocal keyword
Greatest common divisor Python recursive
Python String isalpha() Method
Program to print ASCII Value of a character
Python program to sort words in alphabetical order
*args and **kwargs in Python
Printing Simple Diamond Pattern in Python
Stemming and Lemmatization in Python
Python | Generate QR Code using pyqrcode module




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to add multiple custom markers on google map
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP MYSQL Advanced Search Feature
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple PHP File Cache
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
PHP Secure User Registration with Login/logout
-----------------
Simple way to send SMTP mail using Node.js
-----------------
How to print specific part of a web page in javascript
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
Get Visitor\'s location and TimeZone
-----------------
SQL Injection Prevention Techniques
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
PHP Programming Error Types
-----------------
Date Timestamp Formats in PHP
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.