Как перемешать список python
Перейти к содержимому

Как перемешать список python

  • автор:

Перемешать список Python

В этом посте мы обсудим, как перетасовать список в Python. Решение должно на месте перетасовать содержимое списка.

1. Использование random.shuffle

Стандартным решением для перетасовки списка в Python является использование shuffle() функцию от random модуль. Это показано ниже:

2. Использование random.sample

The shuffle() Функция перемешивает список на месте, т. е. элементы переставляются внутри списка. Чтобы перетасовать неизменяемый список, используйте sample() вместо этого, который вернет новый рандомизированный список. Это показано ниже:

3. Использование numpy.random.shuffle

Если вы используете библиотеку NumPy, рассмотрите возможность использования numpy.random.shuffle . Он изменяет список на месте, перемешивая его содержимое.

Это все о перетасовке списка в Python.

Оценить этот пост

Средний рейтинг 5 /5. Подсчет голосов: 20

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования ��

Как перемешать список в Python

Список – это упорядоченная последовательность элементов. Вы можете перемешать эти элементы, используя функцию shuffle() модуля random.

Функция принимает последовательность и меняет порядок элементов.

Ниже приведен фрагмент быстрого кода для перемешивания списка.

Пример 1

В этом примере мы перемешаем список в Python, используя случайный пакет.

Когда указанная выше программа запускается, она печатает перемешанный список. Мы запускали его много раз, чтобы увидеть, как меняется порядок элементов.

Shuffling a list of objects

How do I shuffle a list of objects? I tried random.shuffle :

Mateen Ulhaq's user avatar

25 Answers 25

random.shuffle should work. Here’s an example, where the objects are lists:

Note that shuffle works in place, and returns None .

More generally in Python, mutable objects can be passed into functions, and when a function mutates those objects, the standard is to return None (rather than, say, the mutated object).

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

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Exercises and Quizzes

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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *