深度阅读

Python program to select from a list

作者
作者
2023年08月22日
更新时间
9.84 分钟
阅读时间
0
阅读量

To select a random element from a list in Python, you can use the random module along with the choice() function. Here’s an example:

import random

my_list = ['apple', 'banana', 'cherry']
random_element = random.choice(my_list)
print(random_element)  # Output: a randomly selected string element from my_list

In this example, we first import the random module. We then define a list my_list containing string elements. We use the choice() function from the random module to select a random element from the list, and store it in random_element. Finally, we print random_element, which contains a randomly selected string element from my_list.

Note that you can modify the my_list variable to contain any kind of elements, including integers and other objects. Also, you can use the randint() function from the random module to select a random integer index from the list, and then use that index to access the corresponding element in the list.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。