What is the recommended way to randomize a list of strings using Python?

0 votes
Hi all, with regard to the above topic - my question is simple. Let me elaborate - So my input in this particular case is a list of strings. And the output I expect is a list with the same strings but in random order.

In case if there are any duplicates then it must be considered too - As in, if the same string can appear more than once in the input, the same follows through in the output as well.

I am aware of methods to go about achieving this like using loops for example. And this is what I am actually doing for now.

I am also aware that Python is amazingly easy to work with and there is a one-line statement which is used to cover this job. So, help?
Jan 18 in Python by Anirudh
• 2,070 points
43 views

1 answer to this question.

0 votes

Hi. Nice question.

Here is the simplified answer for you:

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

Random.shuffle does this exact job.

However, if you are open to more reading then I suggest reading the Fisher-Yates Shuffle methodology. 

Hope this helped!

answered Jan 18 by Nymeria
• 3,520 points

Related Questions In Python

0 votes
1 answer

What is the preferred way to concatenate strings in python??

If the strings you are concatenating are ...READ MORE

answered Dec 20, 2018 in Python by charlie_brown
• 7,720 points
67 views
0 votes
1 answer

Is there a way to list out in-built variables and functions of Python?

The in-built variables and functions are defined ...READ MORE

answered May 14 in Python by Junaid
30 views
0 votes
1 answer

What is the meaning of “int(a[::-1])” in Python?

Assumming a is a string. The Slice ...READ MORE

answered Aug 27, 2018 in Python by Priyaj
• 56,520 points
65 views
0 votes
1 answer

Is arr.__len__() the preferred way to get the length of an array in Python?

my_list = [1,2,3,4,5,6,7] len(my_list) # 7 The same works for ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 13,160 points
52 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 175 views
+4 votes
6 answers
0 votes
1 answer

What is the equivalent of NotImplementedError using Python?

Hi, good question! One simple answer to your ...READ MORE

answered Jan 17 in Python by Nymeria
• 3,520 points
34 views