Randomly select a list item in Python

Опубликовано: 28 Сентябрь 2024
на канале: Better Stack
7,517
272

In this tutorial, we'll explore how to select a random item from a list of six items in Python. Unlike other programming languages that might use a math.random function, Python requires you to import the random module.

You can then utilize the random.choice function, which accepts a sequence—like a list, tuple, or string—and returns a random element from it. However, it's important to note that you should not use this method for generating passwords or tokens. For such purposes, import the secrets module and use secrets.choice instead, as it is cryptographically secure and significantly harder for hackers to predict the output.