Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 580
cqcn1991 Avatar asked May 15 '15 06:05

cqcn1991


People also ask

What does random shuffle return?

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.

How do you shuffle a list in shuffle in Python?

sample() . random. shuffle() shuffles a list in place, and random. sample() returns a new randomized list.


1 Answers

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

like image 53
Veky Avatar answered Oct 12 '22 09:10

Veky