How to shuffle list python

How to shuffle list python

Python random.shuffle() function to shuffle list

Updated on: June 16, 2021 | 6 Comments

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.

FunctionDescription
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.

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 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.

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.

Shuffle a Dictionary in Python

Shuffling a dictionary is not possible in Python. However, we can rearrange the order of keys of a dictionary.

Output:

Shuffle a Python generator

As the generator cannot provide us the size we need to convert it into a list to shuffle it.

Next Steps

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.

Python Random shuffle() Method

Example

Shuffle a list (reorganize the order of the list items):

mylist = [«apple», «banana», «cherry»]
random.shuffle(mylist)

Definition and Usage

The shuffle() method takes a sequence, like a list, and reorganize the order of the items.

Note: This method changes the original list, it does not return a new list.

Syntax

Parameter Values

ParameterDescription
sequenceRequired. A sequence.
functionOptional. The name of a function that returns a number between 0.0 and 1.0.
If not specified, the function random() will be used

More Examples

Example

You can define your own function to weigh or specify the result.

If the function returns the same number each time, the result will be in the same order each time:

def myfunction():
return 0.1

mylist = [«apple», «banana», «cherry»]
random.shuffle(mylist, myfunction)

We just launched
W3Schools videos

COLOR PICKER

How to shuffle list python. Смотреть фото How to shuffle list python. Смотреть картинку How to shuffle list python. Картинка про How to shuffle list python. Фото How to shuffle list python

Get certified
by completing
a course today!

CODE GAME

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Web Courses

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

How to shuffle a list in Python

I know there is a a function that I can import to shuffle the deck, but the way I am required to do it is to take out 1 random card and append it to a new list to have a shuffled list.

How to shuffle list python. Смотреть фото How to shuffle list python. Смотреть картинку How to shuffle list python. Картинка про How to shuffle list python. Фото How to shuffle list python

2 Answers 2

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

I’m not going to solve your homework, but let me give you some hints:

while x: will loop as long as x is true-ish. A non-empty list is true-ish.

you can choose a random number x where 0 by doing x = random.randrange(n) (docs)

You can remove the item with index i from a list l (i.e. l[i] ) by using l.pop(i) (docs)

Another answer that doesn’t answer the OP question.

We start importing the randrange function from the random module,

When we choose a first random index, between 0 and n-1 included, we have that the next index would be chosen in a narrower interval, and so on and so on.

The numbers in l cannot be used directly to address the list to shuffle, because they refer to the position in the list of available elements at a certain point of the shuffling procedure, so for each number in n we have to see how many elements have already been shuffled, and their position relative to the current element, let’s say that we want to store the _real_indices in a list, initially empty

we have to be careful.

and that’s all for shuffling.

Here I report a short IPython session that demonstrates the correctness of this approach:

I’m trying to shuffle only elements of a list on 3rd till last position so the 1st two will always stay in place e.g.

and for some reason this doesn’t work:

Any know what am I doing wrong??

The only thing that works for me is so far this (EDITED):

Think this is exactly what I needed.

How to shuffle list python. Смотреть фото How to shuffle list python. Смотреть картинку How to shuffle list python. Картинка про How to shuffle list python. Фото How to shuffle list python

8 Answers 8

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

What you do is this:

which does not do much to the original list. Try this:

If you want to shuffle without copying, you may try to write your own mutable slice class, like follows (that’s a rough implementation sketch, no boundary checks etc):

Then wrap the original list into it and feed to the standard shuffle:

To shuffle a slice of the list in place, without copies, we can use a Knuth shuffle:

It does the same thing as random.shuffle, except on a slice:

l[2:] constructs a new list, and random.shuffle tries to change the list «in-place,» which has no effect on l itself.

You could use random.sample for this:

You can create your own shuffle function that will allow you to shuffle a slice within a mutable sequence. It handles sampling the slice copy and reassigning back to the slice. You must pass slice() arguments instead of the more familiar [2:] notation.

Using the fact that a list has fast remove and insert and exteding a previous solution (https://stackoverflow.com/a/25229111/3449962):

This will use in-place operations with memory overhead that depends on the number of fixed elements in the list. Linear in time. A possible more general implementation of shuffle_subset:

How to lightly shuffle a list in python

I have this issue where I would like to shuffle a list, but only do so slightly. Say, I want only a small number of elements to be moved. Is there a simple way to get this done?

Right now the best I can think of is building my own method be hand, but is there some way to use the random library to do this for me?

How to shuffle list python. Смотреть фото How to shuffle list python. Смотреть картинку How to shuffle list python. Картинка про How to shuffle list python. Фото How to shuffle list python

6 Answers 6

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

to show what some of these solutions are doing I find it helps to run a monte-carlo algorithm many times and look at the distribution

first a tidied up version of @meta4’s solution as it was the most fleshed out:

which we can run many times by doing:

if we print out the occurrences table as percentages we get:

each row represents the probability of the item moving to the column. in this case (when n=8 ) the algorithm will tend to leave elements where they were

33% of the time, and then pick the remainder uniformly

I can then run (a tidied up) version of pjs’s code with:

which gives very different output:

i.e. items tend to remain close to where they started

this sort of table is great at detecting bias in the distribution, which there doesn’t seem to be evidence of above. but, for example, with Artyom’s solution ( shuffle(x, lambda: random() / 5) ) gives the following:

which probably isn’t what the OP wanted. the high probability off diagonal represents rotating the array by one element

One interpretation is to strongly or weakly retain the initial ordering. The weakest retention would be a completely random shuffle, the strongest would be to not deviate from the initial ordering.

This can be accomplished by creating a tuple consisting of the original index scaled by a constant, plus some randomness, followed by the value. Sort the tuples, then iterate through to recover the original values in their new order. If the scale factor for the index is near zero, the new order will be random. If it’s near 1, things will tend to strongly but not perfectly retain their original ordering. If it’s larger, the result becomes unlikely to be shuffled.

Источники информации:

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

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