0
0
PythonHow-ToBeginner · 4 min read

How to Use Random Module in Python: Simple Guide

Use the random module in Python by first importing it with import random. Then, call functions like random.randint() for random integers, random.choice() to pick a random item from a list, or random.shuffle() to reorder a list randomly.
📐

Syntax

First, import the random module. Then use its functions like:

  • random.randint(a, b): returns a random integer between a and b inclusive.
  • random.choice(sequence): picks a random element from a sequence like a list.
  • random.shuffle(list): shuffles the list in place randomly.
python
import random

# Get a random integer between 1 and 10
num = random.randint(1, 10)

# Pick a random item from a list
item = random.choice(['apple', 'banana', 'cherry'])

# Shuffle a list
items = [1, 2, 3, 4, 5]
random.shuffle(items)
💻

Example

This example shows how to generate a random number, pick a random fruit, and shuffle a list of numbers.

python
import random

# Random integer between 1 and 100
random_number = random.randint(1, 100)
print(f"Random number: {random_number}")

# Random choice from a list
fruits = ['apple', 'banana', 'cherry', 'date']
random_fruit = random.choice(fruits)
print(f"Random fruit: {random_fruit}")

# Shuffle a list
numbers = [10, 20, 30, 40, 50]
random.shuffle(numbers)
print(f"Shuffled numbers: {numbers}")
Output
Random number: 42 Random fruit: banana Shuffled numbers: [40, 10, 50, 20, 30]
⚠️

Common Pitfalls

One common mistake is forgetting to import the random module before using its functions. Another is expecting random.shuffle() to return a new list; it changes the list in place and returns None. Also, using random.randint(a, b) includes both a and b, so be careful with the range.

python
import random

# Wrong: forgetting import
# num = randint(1, 5)  # NameError: name 'randint' is not defined

# Wrong: expecting shuffle to return a list
numbers = [1, 2, 3]
shuffled = random.shuffle(numbers)
print(shuffled)  # Prints None
print(numbers)   # List is shuffled

# Right way:
random.shuffle(numbers)
print(numbers)
Output
None [3, 1, 2] [3, 1, 2]
📊

Quick Reference

FunctionDescriptionExample
random.randint(a, b)Returns random integer between a and b inclusiverandom.randint(1, 10)
random.choice(seq)Returns random element from sequencerandom.choice(['a', 'b', 'c'])
random.shuffle(list)Shuffles list in placerandom.shuffle(my_list)
random.random()Returns random float between 0.0 and 1.0random.random()

Key Takeaways

Always import the random module before using its functions.
Use random.randint(a, b) to get a random integer between a and b inclusive.
random.choice(sequence) picks a random item from any sequence like a list or string.
random.shuffle(list) changes the list order in place and returns None.
Check function behavior carefully to avoid common mistakes like expecting return values from shuffle.