Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
random
choice()
communitycreator

What is random.choice() in Python?

Sarah Tanveer

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The in-built choice() function from the random module randomly selects an element from a sequence, such as a list.

Syntax

random.choice(seq)

Arguments

  • seq: the non-empty sequence from which the element is selected, such as a list, string, etc.

Return value

This function returns an element from the sequence. If the sequence is empty, IndexError is raised.

import random
# picking a random element from defined list
testList = [1, 2, 3, 4]
print("List: ", testList)
element = random.choice(testList)
print("Selected element from list: ", element)
# picking a random letter from string
testStr = "Educative"
print("Str: ", testStr)
element = random.choice(testStr)
print("Selected element from string: ", element)
# using choice() to pick a random number from a range:
num = random.choice(range(0, 101))
print("Random number from 0 to 100: ", num)

Note: the output will be different every time the code is run.

RELATED TAGS

python
random
choice()
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring