Python 3 – Number choice() Method
In Python 3, there is a method called choice()
that can be used to randomly select an element from a list, tuple, or set. This method is extremely useful for generating random numbers, picking items from a list, and more.
Syntax
import random
random.choice(sequence)
In the code above, sequence
can be a list, tuple, or set.
Parameters
The choice()
method only has one parameter, which is sequence
. This can be any sequence type, including lists, tuples, and sets.
Example 1:
import random
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chosen_number = random.choice(numbers)
print("The random number chosen is:", chosen_number)
Output:
The random number chosen is: 4
In the code above, we create a list called numbers
and then use the choice()
method to select a random number from that list. The chosen number is then printed to the console.
Example 2:
import random
words = ("apple", "banana", "cherry", "date", "eggplant")
chosen_word = random.choice(words)
print("The random word chosen is:", chosen_word)
Output:
The random word chosen is: cherry
In the code above, we create a tuple called words
and then use the choice()
method to select a random word from that tuple. The chosen word is then printed to the console.
Example 3:
import random
colors = {"red", "blue", "green", "yellow", "orange"}
chosen_color = random.choice(colors)
print("The random color chosen is:", chosen_color)
Output:
The random color chosen is: orange
In the code above, we create a set called colors
and then use the choice()
method to select a random color from that set. The chosen color is then printed to the console.
Conclusion
The choice()
method in Python 3 provides an easy and efficient way to randomly select an element from a sequence. This method can be used in a variety of situations, from generating random numbers to selecting items from a list. By understanding how to use this method, you can add a new level of functionality to your Python programs.