82

I receive as input a list of strings and need to return a list with these same strings but in randomized order. I must allow for duplicates - same string may appear once or more in the input and must appear the same number of times in the output.

I see several "brute force" ways of doing that (using loops, god forbid), one of which I'm currently using. However, knowing Python there's probably a cool one-liner do get the job done, right?

Roee Adler
  • 32,498
  • 32
  • 101
  • 132
  • 2
    Possible duplicate of [Shuffling a list of objects in python](http://stackoverflow.com/questions/976882/shuffling-a-list-of-objects-in-python) – Assem Jan 18 '16 at 20:16

6 Answers6

214
>>> import random
>>> x = [1, 2, 3, 4, 3, 4]
>>> random.shuffle(x)
>>> x
[4, 4, 3, 1, 2, 3]
>>> random.shuffle(x)
>>> x
[3, 4, 2, 1, 3, 4]
John Kugelman
  • 330,190
  • 66
  • 504
  • 555
  • 1
    random.shuffle(range(5)) .. does not seem to work with on the fly generated list :( – sten Apr 25 '14 at 19:08
  • 7
    @user1019129 `random.shuffle` shuffles lists in place. In Python 3, `range(5)` is a generator, not a list. In Python 2, `range(5)` is a list, but the shuffle is in place, so it shuffles a temporary list which is immediately thrown away. You can do `x = range(5); random.shuffle(x)` and then use `x`. – John Kugelman Apr 25 '14 at 20:35
13

Looks like this is the simplest way, if not the most truly random (this question more fully explains the limitations): http://docs.python.org/library/random.html#random.shuffle

Richard
  • 50,293
  • 28
  • 163
  • 235
Tyler
  • 21,306
  • 11
  • 59
  • 88
7

Given a string item, here is a one-liner:

''.join([str(w) for w in random.sample(item, len(item))])
marr75
  • 5,637
  • 1
  • 24
  • 41
Yann VR
  • 466
  • 5
  • 8
3

You'll have to read the strings into an array and then use a shuffling algorithm. I recommend Fisher-Yates shuffle

Charles Ma
  • 44,439
  • 22
  • 83
  • 99
  • 1
    Based on a glance at the Wikipedia article, it looks like that's more or less what it's doing anyway. You can read the code in C:\Python26\Lib\random.py (or equivalent for other OS's) and it looks like it's doing the same thing described here: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modern_method – Tyler Jun 20 '09 at 18:26
1

In python 3.8 you can use the walrus to help cram it into a couple of lines First you have to create a list from the string and store it into a variable. Then you can use random to shuffle it. Then just join the list back into a string.

random.shuffle(x := list("abcdefghijklmnopqrstuvwxyz"))
x = "".join(x)
Mikeologist
  • 369
  • 3
  • 11
0
import random

b = []
a = int(input(print("How many items you want to shuffle? ")))
for i in range(0, a):
    n = input('Please enter a item: ')
    b.append(n)

random.shuffle(b)

print(b)
hotfix
  • 3,350
  • 18
  • 33