11

Before I ask my question, let me get this straight...

This is not a duplicate of Does anyone know a way to scramble the elements in a list? and Shuffle an array with python, randomize array item order with python. I'll explain why...

I want to know how to scramble an array, and make a new copy. Because random.shuffle() modifies the list in place (and returns None), I want to know if there is another way to do this so I can do scrambled=scramblearray(). If there isn't a built-in function, I could define a function to do this if possible.

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
CoffeeRain
  • 4,460
  • 4
  • 31
  • 50
  • 4
    What's wrong with making a new copy, then scrambling it? – Marcin Mar 19 '12 at 13:02
  • 1
    possible duplicate of [Shuffle an array with python](http://stackoverflow.com/questions/473973/shuffle-an-array-with-python) – Marcin Mar 19 '12 at 13:04
  • @Marcin Personally, I don't think that these answers could be merged with the answers on [Shuffle an array with Python](http://stackoverflow.com/questions/473973/shuffle-an-array-with-python) – CoffeeRain Mar 19 '12 at 13:17
  • Yes, they could. They happen to also demonstrate that you can copy an array. There is no reason why you couldn't have figured this out by yourself. – Marcin Mar 19 '12 at 13:18
  • 1
    I think you should possible make a new copy of the array and scramble it using `random.shuffle()`. It works fine. If you don't like that way, you should probably explain clearly why you don't want. That will help us to understand. – Surya Mar 19 '12 at 13:19

3 Answers3

24
def scrambled(orig):
    dest = orig[:]
    random.shuffle(dest)
    return dest

and usage:

import random
a = range(10)
b = scrambled(a)
print a, b

output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [6, 0, 2, 3, 1, 7, 8, 5, 4, 9]
eumiro
  • 207,213
  • 34
  • 299
  • 261
11

Use sorted(). It returns a new list and if you use a random number as key, it will be scrambled.

import random
a = range(10)
b = sorted(a, key = lambda x: random.random() )
print a, b

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [5, 9, 0, 8, 7, 2, 6, 4, 1, 3]
koffein
  • 1,792
  • 13
  • 21
3

Copy the array then scramble it:

import random

array = range(10)   
newarr = array[:] # shallow copy should be fine for this
random.shuffle(newarr)
#return newarr if needs be.
zip(array, newarr) # just to show they're different

Out[163]:
[(0, 4),
 (1, 8),
 (2, 2),
 (3, 5),
 (4, 1),
 (5, 6),
 (6, 0),
 (7, 3),
 (8, 7),
 (9, 9)]
Marcin
  • 48,559
  • 18
  • 128
  • 201