Python .choice()
Published Oct 15, 2021Updated Mar 9, 2022
Contribute to Docs
The .choice() method returns a random item chosen from an iterable argument, such as a list or a dictionary.
Syntax
random.choice(iterable)
An iterable can be any kind of sequence-oriented variable, including:
- A string of characters (
"Hello, World!"). - A range of steps (
range(10)). - A list of items (
[0, 1]). - A tuple of data values (
(0, "one")).
Example 1
In the example below, .choice() returns an item sampled at random from a list called shopping_list:
import randomshopping_list = ["milk", "eggs", "bread", "apples"]to_buy = random.choice(shopping_list)print(to_buy)
After to_buy is assigned one of the four shopping items with .choice(), it is printed.
Example 2
Since strings are lists of single characters, they can be passed as arguments to the .choice() method:
import randommy_string = "Coding!"print(random.choice(my_string))
Codebyte Example
In the example below, .choice() is used to return a random element from the to_learn tuple:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours