Best way to randomize a list of strings in Python

PythonStringRandom

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

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

''.join([str(w) for w in random.sample(item, len(item))])

Solution 4 - Python

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

Solution 5 - Python

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)

Solution 6 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoee AdlerView Question on Stackoverflow
Solution 1 - PythonJohn KugelmanView Answer on Stackoverflow
Solution 2 - PythonTylerView Answer on Stackoverflow
Solution 3 - PythonYann VRView Answer on Stackoverflow
Solution 4 - PythonCharles MaView Answer on Stackoverflow
Solution 5 - PythonMikeologistView Answer on Stackoverflow
Solution 6 - Pythoninti piresView Answer on Stackoverflow