PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Random » Python random.shuffle() function to shuffle list

Python random.shuffle() function to shuffle list

Updated on: December 4, 2026 | 6 Comments

In this tutorial, you’ll learn how to shuffle a list in Python using random.shuffle(), and how to shuffle strings, ranges, dictionaries, generators and NumPy arrays. Shuffling means putting the items in a random order, like shuffling a deck of cards.

FunctionDescription
random.shuffle(list1)Shuffle a list in place (preferred way)
random.sample(seq, len(seq))Return a new shuffled list and leave the original unchanged; also works with immutable sequences such as strings and ranges
rng.shuffle(array)Shuffle a NumPy array in place (along the first axis)
rng.permutation(array)Return a shuffled copy of a NumPy array
Ways to shuffle a list in Python

Also, Solve:

  • Python random data generation Exercise
  • Python random data generation Quiz

Table of contents

  • The random.shuffle() function
  • Shuffle a list
  • Shuffle a list without changing the original
    • Option 1: Make a copy of the original list
    • Option 2: Use random.sample()
  • Shuffle two lists in the same order
  • Shuffle a NumPy multidimensional array
  • Get the same shuffle result every time
  • Shuffle a string
  • Shuffle a range of integers
  • Shuffle a dictionary
  • Shuffle a generator
  • Limitations of random.shuffle()
  • Summary

The random.shuffle() function

Syntax:

random.shuffle(x)Code language: Python (python)
  • x: a mutable sequence, usually a list.
  • It shuffles x in place and returns None.

Note: Older Python versions accepted a second argument, random, a custom function returning floats. It was deprecated in Python 3.9 and removed in 3.11. Passing it now raises a TypeError.

Shuffle a list

Use the below steps to shuffle a list in Python

  1. Create a list

    Create the list you want to shuffle. For example, list1 = [10, 20, 'a', 'b']

  2. Import random module

    Import the random module using import random.

  3. Use the shuffle() function of a random module

    Call random.shuffle(list1) to shuffle list1 in place. It changes the order of items in the original list and doesn’t return a new list.

  4. Display the shuffled list

    shuffle() returns None, so print the list itself: print(list1).

  5. Get a shuffled list instead of modifying the original list

    Shuffle a copy of the list, or use random.sample() to get a new shuffled list and keep the original unchanged.

Example:

import random

number_list = [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]

# first shuffle
result = random.shuffle(number_list)
print(number_list)
print(result)  # shuffle() returns None

# second shuffle
random.shuffle(number_list)
print(number_list)Code language: Python (python)

Output (your order will differ):

[42, 70, 28, 35, 49, 56, 21, 63, 14, 7]
None
[14, 70, 49, 63, 21, 56, 35, 28, 42, 7]

Common mistake: new_list = random.shuffle(old_list) sets new_list to None. Shuffle first, then use the list.

Shuffle a list without changing the original

Because shuffle() changes the original list, use one of these options when you need to keep it.

Option 1: Make a copy of the original list

import random

numbers = [33, 66, 99, 188, 256, 412, 748]

new_list = numbers.copy()
random.shuffle(new_list)

print("Original list:", numbers)
print("Shuffled list:", new_list)Code language: Python (python)

Output:

Original list: [33, 66, 99, 188, 256, 412, 748]
Shuffled list: [188, 412, 66, 748, 33, 99, 256]

Option 2: Use random.sample()

random.sample() returns a new list of k random items. When k equals the length of the list, the result is a shuffled copy.

import random

numbers = [33, 66, 99, 188, 256, 412, 748]
shuffled = random.sample(numbers, k=len(numbers))
print(shuffled)Code language: Python (python)

Output:

[99, 188, 412, 66, 748, 33, 256]

Shuffle two lists in the same order

Suppose one list holds employee names and another holds their salaries. To shuffle both while keeping each name next to its salary, zip() them into pairs, shuffle the pairs, then unzip them.

import random

employees = ['Jon', 'Emma', 'Kelly', 'Jason']
salary = [7000, 6500, 9000, 10000]

pairs = list(zip(employees, salary))
random.shuffle(pairs)

# unzip back into two lists
names, salaries = map(list, zip(*pairs))
print(names)
print(salaries)Code language: Python (python)

Output:

['Jason', 'Kelly', 'Jon', 'Emma']
[10000, 9000, 7000, 6500]

Shuffle a NumPy multidimensional array

Create a NumPy Generator with default_rng(). Its shuffle() method shuffles an array in place along the first axis, so the rows of a 2D array change order but each row stays intact. Use permutation() to get a shuffled copy instead.

import numpy as np

rng = np.random.default_rng()

array = np.arange(100, 160, 10).reshape(3, 2)
print("Before shuffling:\n", array)

rng.shuffle(array)
print("After shuffling:\n", array)

# shuffled copy (original unchanged)
print(rng.permutation(np.arange(1, 6)))Code language: Python (python)

Output:

Before shuffling:
 [[100 110]
 [120 130]
 [140 150]]
After shuffling:
 [[140 150]
 [120 130]
 [100 110]]
[4 1 3 2 5]

Get the same shuffle result every time

Python’s random module is a pseudo-random number generator (PRNG): its output is fully determined by a starting value called the seed. By default, the seed comes from the operating system. If you set the seed yourself, the same list always shuffles into the same order.

import random

numbers = [10, 20, 30, 40, 50, 60]

for i in range(3):
    shuffled = numbers.copy()
    random.seed(4)
    random.shuffle(shuffled)
    print(shuffled)Code language: Python (python)

Output:

[40, 60, 50, 10, 30, 20]
[40, 60, 50, 10, 30, 20]
[40, 60, 50, 10, 30, 20]

Note: Shuffle a fresh copy each time. If you re-shuffle the already shuffled list, the same seed produces a different final order because the starting order is different.

Shuffle a string

Strings are immutable, so random.shuffle() can’t change them and raises TypeError: 'str' object does not support item assignment. Convert the string to a list of characters, shuffle it, and join it back. Or use sample() to do it in one line.

import random

sample_str = "PYnative"

# approach 1: convert to a list, shuffle, join
char_list = list(sample_str)
random.shuffle(char_list)
print(''.join(char_list))

# approach 2: random.sample()
print(''.join(random.sample(sample_str, k=len(sample_str))))Code language: Python (python)

Output:

tYeaivPn
PYtinvea

Shuffle a range of integers

A range is immutable too, so shuffle(range(10)) raises a TypeError. Convert it to a list first.

import random

numbers = list(range(10))
random.shuffle(numbers)
print(numbers)Code language: Python (python)

Output:

[8, 5, 9, 7, 1, 2, 6, 4, 0, 3]

Shuffle a dictionary

You can’t shuffle a dictionary directly, but since Python 3.7 dictionaries keep insertion order. So shuffle the keys and build a new dictionary in that order.

import random

student_dict = {'Eric': 80, 'Scott': 75, 'Jessa': 95, 'Mike': 66}

keys = list(student_dict)
random.shuffle(keys)

shuffled_dict = {key: student_dict[key] for key in keys}
print(shuffled_dict)Code language: Python (python)

Output:

{'Mike': 66, 'Scott': 75, 'Eric': 80, 'Jessa': 95}

Shuffle a generator

shuffle() needs to know the length of the sequence, so a generator raises TypeError: object of type 'generator' has no len(). Convert the generator to a list first.

import random

def sample_generator():
    yield 25
    yield 50
    yield 75
    yield 100

items = list(sample_generator())
random.shuffle(items)
print(items)Code language: Python (python)

Output:

[50, 25, 75, 100]

Limitations of random.shuffle()

  • Long sequences: The number of possible orders grows very fast. For lists longer than about 2,080 items, there are more possible orders than the Mersenne Twister generator can produce, so some orders can never appear. This rarely matters in practice.
  • Security: The random module is predictable. To shuffle for anything security-sensitive, use random.SystemRandom().shuffle(x). See cryptographically secure random data in Python.

Practice Problem:

Create a deck of 52 cards (ranks 2–10, J, Q, K, A in four suits), shuffle it, and deal 5 cards.

Show Solution
import random

ranks = [str(n) for n in range(2, 11)] + ["J", "Q", "K", "A"]
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
deck = [f"{rank} of {suit}" for suit in suits for rank in ranks]

random.shuffle(deck)
hand = deck[:5]
print(hand)Code language: Python (python)

Summary

  • random.shuffle(x) shuffles a list in place and returns None.
  • To keep the original, shuffle a copy or use random.sample(x, k=len(x)).
  • Convert strings, ranges, dictionary keys and generators to a list before shuffling.
  • Use random.seed() for repeatable shuffles and NumPy’s rng.shuffle() or rng.permutation() for arrays.

Now test what you’ve learned with the Python random data generation exercise and quiz.

Filed Under: Python, Python Random

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Random

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python Random
TweetF  sharein  shareP  Pin

  Python Random Data

  • Guide to Generate Random Data
  • Random randint() & randrange()
  • Random Choice
  • Random Sample
  • Weighted random choices
  • Random Seed
  • Random Shuffle
  • Get Random Float Numbers
  • Generate Random String
  • Generate Secure random data
  • Secrets to Secure random data
  • Random Data Generation Exercise
  • Random Data Generation Quiz

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com