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 >>>
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.
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.
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.
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.
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With