Coding with AI

Code Faster. Think Smarter. Ship Better—with AI.

Stop fighting boilerplate and busywork. Coding with AI shows professional Python developers how to use AI tools to accelerate design, coding, testing, debugging, and documentation—without sacrificing quality or control. Learn proven prompts, real workflows, and practical techniques you’ll use on the job every day.

Explore the book ->


Choosing a Random Element from a List in Python

In this article, we’ll cover selecting a random element from an existing list. This can be useful for tasks such as creating quizzes, lottery systems, or just general fun programming challenges. …

Updated October 7, 2023

In this article, we’ll cover selecting a random element from an existing list. This can be useful for tasks such as creating quizzes, lottery systems, or just general fun programming challenges.

In Python, you can use the built-in function random.choice() to select a random element from a given list. Here’s how it works:

import random
my_list = ['a', 'b', 'c', 'd']
print(random.choice(my_list))

After running this code, you’ll see any one of the elements printed out - this is chosen randomly from the list.

This function uses a “weighted” random choice, meaning it has equal probability of choosing each item in the list. If you want different probabilities for different items (e.g., selecting ‘a’ more than ‘b’), you can use random.choices() instead, which takes an optional weights argument.

my_list = ['a', 'b', 'c']
weights = [3, 1, 2] # Each element in the list corresponds to its weight
print(random.choices(my_list, weights=weights))

This would give you an output of either 'a', 'b', or 'c', with a 3-to-1-to-2 chance for each item respectively.

Remember that if the list is empty, this will raise a IndexError. If you want to avoid this error, you can specify a default value using random.choice(my_list, None).

Coding with AI

AI Is Changing Software Development. This Is How Pros Use It.

Written for working developers, Coding with AI goes beyond hype to show how AI fits into real production workflows. Learn how to integrate AI into Python projects, avoid hallucinations, refactor safely, generate tests and docs, and reclaim hours of development time—using techniques tested in real-world projects.

Explore the book ->