Python random.shuffle() function to shuffle list
In this lesson, you will learn how to shuffle a list in Python using the random.shuffle() function. Also, learn how to shuffle string, dictionary, or any sequence in Python.
When we say shuffle a list, it means a change in the order of list items. For example, shuffle a list of cards.
You’ll learn the following functions of a random module to randomize a list in Python.
| Function | Description |
|---|---|
| random.shuffle(list1) | Shuffle list in-place (preferred way) |
| random.sample(seq, len(seq)) | Shuffle list not in place to return a new shuffled list. (non-preferred way) OR To shuffle an immutable sequence such as string or range. |
| np.random.shuffle(array) | Shuffling multidimensional array |
ways to shuffle a list in Python
Also, See:
Table of contents
The random.shuffle() function
Syntax
It means shuffle a sequence x using a random function.
Parameters:
The random.shuffle() function takes two parameters. Out of the two, random is an optional parameter.
- x : It is a sequence you want to shuffle such as list.
- random : The optional argument random is a function returning a random float number between 0.1 to 1.0. This function decides how to shuffle a sequence. If not specified, by default Python uses the random.random() function.
Note: this parameter deprecated since version 3.9, will be removed in version 3.11
Return Value
It shuffles sequence in place and doesn’t return anything, i.e., It returns None. This function changes the position of items in a mutable sequence.
Shuffle a List
Use the below steps to shuffle a list in Python
-
Create a list
Create a list using a list() constructor. For example, list1 = list([10, 20, ‘a’, ‘b’])
Use a random module to perform the random generations on a list
Use the random.shuffle(list1) function to shuffle a list1 in place.
the shuffle() shuffles the original list, i.e., it changes the order of items in the original list randomly and doesn’t return a new list
As shuffle() function doesn’t return anything. Use print(list1) to display the original/resultant list.
Use the random.sample() function to shuffle the list not in place to get the new shuffled list in return instead of changing the original list. OR
Make a copy of the original list before shuffling (Ideal way)
If you want to perform shuffling as per your need, you can pass a custom function in the place of the random argument, which will dictate the shuffle() function on how to randomize a list’s items.
Example: –
Note: As you can see in the output, the positions of list items are changed.
Randomly Shuffle Not in Place
As you know, the shuffle() works in place and returns None, i.e., it changes the order of items in the original list randomly. But most of the time, we need the original list or sequence.
We can keep the original list intact using the following two ways. These options don’t modify the original list but return a new shuffled list.
Option 1: Make a Copy of the Original List
Make a copy of the original list before shuffling (Ideal and preferred)
Option 2: Shuffle list not in Place using random.sample()
Use the random.sample() function to shuffle list not in place to get the new shuffled list in return instead of changing the original list
The random.sample() function returns the random list with the sample size you passed to it. For example, sample(myList, 3) will return a list of 3 random items from a list.
If we pass the sample size the same as the original list’s size, it will return us the new shuffled list.
Let’s see the example. In this example, I am shuffling the list of Employee objects.
Waring : As per the official Python documentation, for small len(x) , the total number of permutations of x can quickly grow more extensive than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the Mersenne Twister random number generator period. So I advise you to use the use first approach.
Shuffle Two Lists At Once With Same Order
Let’s assume if you want to Shuffle two lists and maintain the same shuffle order. For example, One list contains employee names, and the other includes a salary. Let’s see how to randomize multiple lists by maintaining their order.
Shuffling NumPy Multidimensional Array
NumPy module has a numpy.random package to generate random data. In this example, I am using Python’s Numpy module to create a 2d array. Also, Using numpy.random.shuffle() function, we can shuffle the multidimensional array.
Output:
Shuffle a List to Get the Same Result Every time
Let’s how to seed the random generator in such a way that shuffling produces the same result every time. Using the seed() and shuffle() together, we can generate the same shuffled list every time.
Do you know how PRNG works in Python?
Python’s random module is not truly random. It is pseudo-random (PRNG), i.e., deterministic. The random module uses the seed value as a base to generate a random number. By default, current system time is used as a seed value. If we change the seed value, we can change the output.
Output:
Note: We are getting the same list because we use the same seed value before calling the shuffle function. This is just a simple example. To make it work with any list, we need to find the exact seed root number for that list, which will produce the output we desire.
Shuffle a String
In this section, we will see how to shuffle String in Python. But it is not as simple as shuffling a list. You will get an error if you try to shuffle a string using the shuffle() method.
Because a string is an immutable type, and You can’t modify the immutable objects in Python. The random.shuffle() doesn’t’ work with String. I.e., It can’t accept string argument. Let’s understand this with the help of the following example.
We have a solution to this. We can shuffle a string using various approaches. Let see each one by one.
Shuffle a String by Converting it to a List
Convert String to list and Shuffle the list randomly, again convert the shuffled list into String
Approach Two: Shuffling a String, not in place
Using this approach, we can keep the original string unchanged and get the new shuffled string in return. Also, we don’t need to convert the string to a list to get the shuffled string.
The sample() function returns a sample from a sequence as per the sample size you passed to it. For example, sample(str, 3) will return a list of 3 random characters from a list.
If we pass the sample size the same as the string size, it will return us the new shuffled string of characters.
Shuffle Range of Integers
A range() function returns a sequence of numbers.
The range() doesn’t return the list, so when you try to run shuffle(range(10)) , you will get an error. To shuffle numbers in the range(10) , first convert the range to a list .
Shuffle a Dictionary in Python
Shuffling a dictionary is not possible in Python. However, we can rearrange the order of keys of a dictionary.
- Fetch all keys from a dictionary as a list.
- Shuffle that list and access dictionary values using shuffled keys.
Output:
Shuffle a Python generator
The random.shuffle() needs to know the sequence’s size to shuffle the sequence uniformly. If you try to shuffle a generator object using it, you will get a TypeError: the object of type ‘generator’ has no len() .
As the generator cannot provide us the size we need to convert it into a list to shuffle it.
Next Steps
I want to hear from you. What do you think of this article on random.shuffle() ? Or maybe I missed one of the usages of random.shuffle() . Either way, let me know by leaving a comment below.
Also, try to solve the following exercise and quiz to have a better understanding of working with random data in Python.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
Перемешать буквы python
![]()
Строки неизменяемы в Питоне, поэтому чтобы перемешать буквы в словах текста, каждое слово преобразуются в список символов, список перемешивается, затем объединённые символы назад в список слов присваиваются.
В общем случае, слова на буквы можно не только посимвольно (на отдельные Unicode code points) разбивать. См. Как разбить строку на отдельные символы?
Функция shuffle() модуля random в Python, перемешивает список
Перемешивает изменяемую последовательность случайным образом
Синтаксис:
Параметры:
- x — изменяемая последовательность (список),
- random — функция, которая выдает случайные числа float (устарел с версии Python 3.9 и будет удален в версии 3.11).
Возвращаемое значение:
- изменяет непосредственно сам объект последовательности.
Описание:
Функция shuffle() модуля random перемешивает изменяемую последовательность x на месте. Функция ничего не возвращает, а изменяет непосредственно сам объект последовательности x .
Функция random.shuffle() способна работать только с изменяемыми последовательностями, такими как списки, т.е. получить перестановку из строки или кортежа не получится. Для перемешивания неизменяемых последовательностей можно использовать функцию random.sample(x, k=len(x)) как показано ниже в примере.
Необязательный параметр random принимает имя функции которая выдает случайные числа с плавающей точкой в диапазоне [0.0, 1.0] , с единственным условием — данная функция не должна принимать параметры. По умолчанию это функция random.random() :
Внимание! Необязательный аргумент random устарел с версии Python 3.9 и будет удален в версии 3.11.
Пример перемешивания последовательности.
Например, получить перестановку элементов списка, другими словами перемешать, можно как-то так:
Что бы перемешать неизменяемую последовательность (строку, кортеж), ее необходимо преобразовать в список:
Python | Scramble strings in list
Sometimes, while working with different applications, we can come across a problem in which we require to shuffle all the strings in the list input we get. This kind of problem can particularly occur in gaming domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehension + sample() + join() The combination of above functions can be used to solve this problem. In this, we need to disintegrate string into character list, scramble using sample(), rejoin them using join() and then remake list using list comprehension.
Python3
Time complexity: O(n), where n is the length of the numbers list. The list comprehension + sample() + join() have a time complexity of O(n)
Auxiliary Space: O(n),where n is the length of the numbers list.
Method #2 : Using list comprehension + shuffle() + join() This is similar to the above method. The only difference is that shuffle() is used to perform scramble task than using sample().
Python3
Using str.maketrans() and str.translate():
In this approach, we will create a translation table using the str.maketrans() method and then apply it to each string using the str.translate() method.
Python3
Time complexity: O(n * k) where n is the number of strings in the list and k is the average length of the strings.
Auxiliary Space: O(k) where k is the maximum length of the strings in the list.
METHOD 3:Using for.
APPROACH:
This Approach tells how to scramble the strings in a given list of strings by shuffling the characters in each string between the first and last characters while keeping the first and last characters of each string in their original position.
ALGORITHM:
1.Import the random module
2.Create an original list of strings
3.Create an empty list to store scrambled strings
4.Iterate over each string in the original list
a. Extract the characters between the first and last characters of the string
b. Shuffle the extracted characters using the shuffle() method from the random module
c. Combine the first character, shuffled characters, and the last character of the string
d. Append the scrambled string to the scrambled list
5.Print the scrambled list