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 import random to use choice() method.
Below is the Python3 implementation of the above approach:
# Python3 program to demonstrate the use of # choice() method # import random import random # prints a random value from the list list1 = [1, 2, 3, 4, 5, 6] print(random.choice(list1)) # prints a random item from the string string = "striver" print(random.choice(string)) |
The output every-time will be different as the system returns a random item.
Output:
5 s
Practical application:
Print any random number 5 times from a given list.
# Python3 program to demonstrate the practical application # choice() # import random module import random list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for x in range(5): print(random.choice(list1)) |
The output changes every time as choice() function is used.
Output:
1 4 1 5 7
Recommended Posts:
- Python map function | Count total set bits in all numbers from 1 to n
- Random Numbers in Python
- Python | N consecutive Odd or Even Numbers
- Python program to add two numbers
- Python | Numbers in a list within a given range
- Complex Numbers in Python | Set 1 (Introduction)
- Python | Indices of numbers greater than K
- Python | Extract numbers from string
- Python | Check whether string contains only numbers or not
- Python | Sort list of numbers by sum of their digits
- Python | Print all string combination from given numbers
- Python | Largest number possible from list of given numbers
- Python | Remove all characters except letters and numbers
- Python | Create list of numbers with given range
- Python | Check if list contains consecutive numbers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



