import random # Suppose we have a list of items items = ['apple', 'banana', 'cherry', 'date', 'elderberry'] # Select a random item from the list selected_item = random.choice(items) print(selected_item)
# Output: a random item from the list
To randomly select an item from a list in Python, you can use the random.choice function from the random module. The random.choice function returns a random element from the list. You can call this function multiple times to select multiple random items from the list.Alternatively, you can also use the random.sample function to select a specified number of random items from the list. Here is an example of how to use random.sample:
import random # Suppose we have a list of items items = ['apple', 'banana', 'cherry', 'date', 'elderberry'] # Select 3 random items from the list selected_items = random.sample(items, 3) print(selected_items) # Output: a list of 3 random items from the list*Note that the random module uses a pseudo-random number generator, which means that the random items selected by these functions are not truly random, but are generated using a deterministic algorithm. If you need truly random values, you can use the secrets module, which generates random values using sources of randomness provided by the operating system.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.