5

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
>>>
Mozein
  • 787
  • 5
  • 19
  • 33

5 Answers5

5

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
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
2

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]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

random.shuffle works in place, meaning it updates the provided parameter, rather than returning a value (other than the default, None). In C++, you would need to pass a reference to the list instead (e.g. int** aList), but in Python this distinction doesn't really exist.

So, you're actually setting shuffleList to None, and then returning it!

You can confirm this by using print to actually show the results when you're finished - just returning the value from the function won't output anything, as far as I am aware:

results = shuffle()
print results

To fix it, just return aList, instead of storing the result in another variable:

random.shuffle(aList)
return aList
Hannele
  • 9,301
  • 6
  • 48
  • 68
2

Shuffle shuffles the list, it doesn't return a new list. Try this:

import random

def shuffle():
    aList = []

    for i in range(0, 5):
        elements = input(": ")
        aList.append(elements)

    random.shuffle(aList)
    return aList

print shuffle()
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • You are printing the function which does not work. returning th elist is enough. I believe thats the problem – Mozein Feb 11 '15 at 20:31
  • I added the print after the downvotes started rolling in and this willwork by the way. You're just printing a list. – Malik Brahimi Feb 11 '15 at 20:32
1

random.shuffle() reorders the list in-place and returns None.

Zachary Cross
  • 2,298
  • 1
  • 15
  • 22