Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to randomize a list of strings in Python

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?

like image 982
Roee Adler Avatar asked Jun 20 '09 18:06

Roee Adler


People also ask

How do you randomize a list in a list Python?

To use shuffle, import the Python random package by adding the line import random near the top of your program. Then, if you have a list called x, you can call random. shuffle(x) to have the random shuffle function reorder the list in a randomized way. Note that the shuffle function replaces the existing list.

Can you randomize strings in Python?

We can Generate Random Strings and Passwords in Python using secrets. choice(). For Cryptographically more secure random numbers, this function of the secret module can be used as its internal algorithm is framed in a way to generate less predictable random numbers.

Does random shuffle work on strings?

Because a string is an immutable type, and You can't modify the immutable objects in Python. The random. shuffle() doesn't' work with String.

How do you shuffle multiple lists in Python?

Method : Using zip() + shuffle() + * operator In this method, this task is performed in three steps. Firstly, the lists are zipped together using zip(). Next step is to perform shuffle using inbuilt shuffle() and last step is to unzip the lists to separate lists using * operator.


1 Answers

>>> 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] 
like image 158
John Kugelman Avatar answered Sep 19 '22 00:09

John Kugelman