ZK Zhao
ZK Zhao

Reputation: 21523

Shuffle a list and return a copy

I want to shuffle an array, but all I find was method like random.shuffle(x), from Best way to randomize a list of strings in Python

Can I do something like

import random
rectangle = [(0,0),(0,1),(1,1),(1,0)]
# I want something like
# disorderd_rectangle = rectangle.shuffle

Now I can only get away with

disorderd_rectangle = rectangle
random.shuffle(disorderd_rectangle)
print(disorderd_rectangle)
print(rectangle)

But it returns

[(1, 1), (1, 0), (0, 1), (0, 0)]
[(1, 1), (1, 0), (0, 1), (0, 0)]

So the original array is also changed. How can I just create another shuffled array without changing the original one?

Upvotes: 13

Views: 16852

Answers (5)

Buğra Gündoğ
Buğra Gündoğ

Reputation: 101

Use random.sample to shuffle a list without changing the original one.

from random import sample
rect = [(0,0),(0,1),(1,1),(1,0)]
shuffled_rect = sample(rect, len(rect))

The code snippet above is slower but just another way.

Upvotes: 9

dawg
dawg

Reputation: 103814

Use a slice to make a shallow copy, then shuffle the copy:

>>> rect = [(0,0),(0,1),(1,1),(1,0)]
>>> sh_rect=rect[:]
>>> random.shuffle(sh_rect)
>>> sh_rect
[(0, 1), (1, 0), (1, 1), (0, 0)]
>>> rect
[(0, 0), (0, 1), (1, 1), (1, 0)]

Upvotes: 4

Saftblandaren
Saftblandaren

Reputation: 103

You need to make a copy of the list, by default python only creates pointers to the same object when you write:

disorderd_rectangle = rectangle

But instead use this or the copy method mentioned by Veky.

disorderd_rectangle = rectangle[:]

It will make a copy of the list.

Upvotes: 3

Veky
Veky

Reputation: 2745

People here are advising deepcopy, which is surely an overkill. You probably don't mind the objects in your list being same, you just want to shuffle their order. For that, list provides shallow copying directly.

rectangle2 = rectangle.copy()
random.shuffle(rectangle2)

About your misconception: please read http://nedbatchelder.com/text/names.html#no_copies

Upvotes: 18

user1907906
user1907906

Reputation:

Use copy.deepcopy to create a copy of the array, shuffle the copy.

c = copy.deepcopy(rectangle)
random.shuffle(c)

Upvotes: 4

Related Questions