Get a Random Element from a List in Python

  • Post category:List

Getting a random element from a list is a common task in Python programming. In this blog post, we’ll explore different code examples that demonstrate how to select a random element from a list efficiently.

Example 1:

import random

fruits = ['apple', 'banana', 'kiwi', 'orange']
random_fruit = random.choice(fruits)

Output: (randomly selected fruit)

Example 2:

import random

numbers = [1, 2, 3, 4, 5]
random_number = random.sample(numbers, 1)[0]

Output: (randomly selected number)