Question

How to Get a Random Element from a List in Python

pythonlistrandom

Question

How can I retrieve a random item from the following Python list?

foo = ['a', 'b', 'c', 'd', 'e']

I want to choose one element at random from the list.

Short Answer

By the end of this page, you will understand how to select a random element from a Python list, which standard library function is usually used for this, how it works step by step, and what mistakes to avoid when the list may be empty or when reproducible results are needed.

Concept

In Python, a common way to get a random item from a list is to use the random module from the standard library. The most direct function for this is random.choice().

import random

foo = ['a', 'b', 'c', 'd', 'e']
item = random.choice(foo)
print(item)

random.choice(sequence) returns one randomly selected element from a non-empty sequence.

A sequence includes types like:

  • list
  • tuple
  • str

This matters because choosing random data is extremely common in programming:

  • picking a quiz question
  • selecting a test case
  • showing a random tip
  • simulating events in a game
  • sampling data for scripts

The key idea is simple: instead of manually generating an index yourself, Python provides a built-in tool that already does that safely and clearly.

If you only need one random element, random.choice() is usually the best and most readable option.

Mental Model

Think of a list like a bag of labeled balls:

  • 'a'
  • 'b'
  • 'c'
  • 'd'
  • 'e'

Using random.choice(foo) is like reaching into the bag and pulling out one ball without caring which position it came from.

You do not need to count positions yourself unless you specifically want the index. Python does the pick for you.

Another way to picture it:

  • the list is a row of boxes
  • each box has an index
  • random.choice() secretly picks one valid box number
  • then returns the value inside that box

So the real job is not "find a random index" but "ask Python for one random element from this sequence."

Take Quiz

Syntax and Examples

The basic syntax is:

import random
random.choice(sequence)

Basic example

import random

foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))

Possible output:

c

If you run it again, you may get a different result.

Store the result in a variable

import random

colors = ['red', 'blue', 'green']
selected_color = random.choice(colors)
print(selected_color)

This is useful when you want to use the chosen value later.

Choosing from other sequence types

import random

print(random.choice((10, 20, 30)))
print(random.choice('hello'))

This works because tuples and strings are also sequences.

If you want a random index instead

Sometimes you need the position as well as the value:

import random

foo = ['a', 'b', 'c', 'd', 'e']
index = random.randrange(len(foo))
item = foo[index]

print(index)
print(item)

Use this approach only when the index itself matters. If you only want the element, random.choice() is clearer.

Reproducible randomness for testing

import random

random.seed(42)
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))

Setting a seed makes results repeatable across runs in many testing scenarios.

Step by Step Execution

Consider this code:

import random

foo = ['a', 'b', 'c', 'd', 'e']
item = random.choice(foo)
print(item)

Here is what happens step by step:

  1. import random

    • Python loads the random module so you can use its functions.
  2. foo = ['a', 'b', 'c', 'd', 'e']

    • A list named foo is created with 5 elements.
    • Their indexes are:
      • 0 -> 'a'
      • 1 -> 'b'
      • 2 -> 'c'
      • 3 -> 'd'
      • 4 -> 'e'
  3. item = random.choice(foo)

    • Python checks that foo is not empty.
    • It picks one valid position at random.
    • For example, it might internally choose index 2.
    • The value at index 2 is 'c'.
    • That value is stored in item.
  4. print(item)

    • Python prints the selected value.
    • In this example, it would print:
c

On another run, Python may choose index 0, 3, or any other valid index, so the output may change.

Real World Use Cases

Random selection from a list appears in many real programs.

Showing a random message

A command-line app might display one random motivational message each time it starts.

import random

messages = ['Keep going!', 'Nice work!', 'You are improving!']
print(random.choice(messages))

Picking a random quiz question

An educational app may store questions in a list and choose one for the user.

Simulating game behavior

A game may choose a random enemy action:

  • attack
  • defend
  • heal

Selecting sample data for tests

During development, you may want one random user ID or one random item from mock data.

Rotating content in web apps

A site might choose a random banner, tip, quote, or featured item.

Simple load distribution or experiments

In small scripts, developers may randomly pick from a list of options to test different paths.

Take Quiz

Real Codebase Usage

In real codebases, developers usually use random selection in small, readable, defensive ways.

Common pattern: direct selection

import random

theme = random.choice(themes)

This is the most common pattern when the list is guaranteed to have values.

Guard clause for empty lists

A robust codebase often checks for empty input first.

import random

if not items:
    return None

return random.choice(items)

This avoids runtime errors.

Validation before selection

If data comes from a file, API, or user input, developers often validate it first.

import random

if not isinstance(items, list) or not items:
    raise ValueError('items must be a non-empty list')

return random.choice(items)

Reproducible behavior in tests

In automated tests, randomness is often seeded.

import random

random.seed(1)
result = random.choice(['a', 'b', 'c'])

Picking multiple values

If a real project needs more than one random item, developers often switch to related functions:

  • random.sample() for unique picks
  • random.choices() for picks with replacement

So in production code, the choice of function depends on whether you need:

  • one item
  • many items
  • repeated values allowed or not
  • predictable test output

Common Mistakes

Here are common beginner mistakes when selecting a random list element in Python.

Mistake 1: Forgetting to import random

Broken code:

foo = ['a', 'b', 'c']
print(random.choice(foo))

Problem:

  • random is not defined.

Fix:

import random

foo = ['a', 'b', 'c']
print(random.choice(foo))

Mistake 2: Calling choice() on an empty list

Broken code:

import random

foo = []
print(random.choice(foo))

Problem:

  • This raises IndexError because there is nothing to choose.

Fix:

import random

foo = []
if foo:
    print(random.choice(foo))
else:
    print('List is empty')

Mistake 3: Using the wrong function name

Broken code:

import random

foo = ['a', 'b', 'c']
print(random.choose(foo))

Problem:

  • The correct function is random.choice(), not random.choose().

Mistake 4: Confusing value and index

Broken thinking:

import random

foo = ['a', 'b', 'c']
item = random.randrange(len(foo))
print(item)

Problem:

  • This prints a random index like 1, not the list value.

Fix:

import random

foo = ['a', 'b', 'c']
index = random.randrange(len(foo))
item = foo[index]
print(item)

Or better:

import random

foo = ['a', 'b', 'c']
print(random.choice(foo))

Mistake 5: Expecting true cryptographic randomness

random.choice() is fine for normal programming tasks, but not for passwords, security tokens, or sensitive secrets.

For security-related random values, use the secrets module instead.

import secrets

foo = ['a', 'b', 'c']
print(secrets.choice(foo))

Mistake 6: Assuming the same result every run

Random output usually changes. If you need reproducible behavior for testing, use a seed.

import random

random.seed(42)
foo = ['a', 'b', 'c']
print(random.choice(foo))

Comparisons

Here is how random.choice() compares with related approaches in Python.

ApproachBest forReturnsNotes
random.choice(seq)One random elementA value from the sequenceMost readable for a single item
random.randrange(len(seq))One random indexAn integer indexUseful only when you need the index
random.sample(seq, k=1)Unique random picksA listReturns a list, even for one item
random.choices(seq, k=1)Random picks with replacementA listCan repeat items when k > 1
secrets.choice(seq)Security-sensitive selectionA value from the sequenceBetter for passwords, tokens, security logic

random.choice() vs random.sample()

import random

foo = ['a', 'b', 'c', 'd']
print(random.choice(foo))      # one value
print(random.sample(foo, 1))   # list containing one value

Use choice() when you want one value directly.

random.choice() vs manual index selection

import random

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

index = random.randrange(len(foo))
print(foo[index])

Both can work, but choice() is simpler and more expressive.

random.choice() vs secrets.choice()

  • Use random.choice() for games, demos, data scripts, and general programming.
  • Use secrets.choice() for authentication, secret generation, and security-sensitive tasks.
Take Quiz

Cheat Sheet

import random
random.choice(sequence)

Quick rules

  • random.choice() returns one random element from a non-empty sequence.
  • Works with:
    • lists
    • tuples
    • strings
  • You must import random first.
  • Empty sequences raise IndexError.

Common examples

import random

foo = ['a', 'b', 'c', 'd', 'e']
item = random.choice(foo)
import random

index = random.randrange(len(foo))
item = foo[index]

Related functions

random.choice(seq)       # one item
random.sample(seq, 2)    # multiple unique items
random.choices(seq, k=2) # multiple items, repeats allowed

Empty-list safety

if foo:
    print(random.choice(foo))
else:
    print('Empty list')

Repeatable output for tests

random.seed(42)

Security-sensitive selection

import secrets
secrets.choice(foo)

FAQ

How do I pick a random item from a Python list?

Use random.choice():

import random
item = random.choice(my_list)

What happens if the list is empty?

random.choice([]) raises IndexError. Check that the list is not empty before calling it.

Do I need to generate a random index manually?

No. If you only need the value, random.choice() is simpler and clearer.

Can I choose more than one random item?

Yes.

  • Use random.sample() for unique items.
  • Use random.choices() if repeats are allowed.

Is random.choice() truly random?

It is suitable for normal programming tasks, but not for cryptographic or security-sensitive use.

How do I get the same random result during testing?

Set a seed first:

import random
random.seed(42)

Can I use random.choice() on tuples or strings?

Yes. It works on non-empty sequences such as lists, tuples, and strings.

Take Quiz

Mini Project

Description

Build a simple Python script that displays a random prompt from a list of study tasks. This demonstrates how to store values in a list, choose one at random, and safely handle the case where the list might be empty.

Goal

Create a script that prints one random study task from a predefined list.

Requirements

  • Create a list with at least five study tasks.
  • Use Python's standard library to select one task at random.
  • Print the selected task.
  • Add a check so the program handles an empty list safely.
Take Quiz

Keep learning

Related questions

View more