Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python shuffle list not working [duplicate]

Tags:

python

I am new with python. coming from a C++ background I'm ironically having trouble understanding the simplicity of this language not to mention how IDLE works.

anyhow I need to write a simple function that takes a list and returns a new list with the elements inside it shuffled

this is what I have so far

import random
def shuffle():
    aList = []
    i = 0
    for i in range(0, 5):
        elements = input(": ")
        aList.append(elements)

    shuffleList = random.shuffle(aList)
    return shuffleList


shuffle()

and after I enter the elements(numerical numbers in this case), nothing outputs.. So the shuffleList for some reason is not being shown in there. Any ideas ?

>>> 
: 1
: 2
: 3
: 4
: 5
>>>
like image 306
Mozein Avatar asked Feb 11 '15 20:02

Mozein


People also ask

Why random shuffle is not working in Python?

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 I randomly shuffle a list in Python?

Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.

How do you shuffle two 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.

How do I shuffle a list in stackoverflow Python?

You could use random. sample(x, len(x)) or just make a copy and shuffle that. For list. sort which has a similar issue, there's now list.


2 Answers

random.shuffle shuffles the list in place, and its output is None.

Since you store and return its output in shuffleList = random.shuffle(aList), nothing is printed.

So instead, return the aList back:

import random
def shuffle():
    aList = []
    i = 0
    for i in range(0, 5):
        elements = input(": ")
        aList.append(elements)
    random.shuffle(aList)
    return aList
like image 134
Anshul Goyal Avatar answered Oct 04 '22 20:10

Anshul Goyal


random.shuffle is an in-place operation, it does not return anything

>>> l
[0, 1, 2, 3, 4]

>>> random.shuffle(l)
>>> l
[0, 3, 1, 4, 2]
like image 22
Cory Kramer Avatar answered Oct 04 '22 20:10

Cory Kramer