.choice()

BrandonDusch580 total contributions
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:
All contributors
- BrandonDusch580 total contributions
- Anonymous contributorAnonymous contributor3077 total contributions
- BalaPriyaC6 total contributions
- BrandonDusch
- Anonymous contributor
- BalaPriyaC
Looking to contribute?
- 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.