from random import *
day = list(range(1, 29))
day = day[3:29]
shuffleday = shuffle(day)
print(shuffleday)
The result is None
. What's wrong?
CodePudding user response:
random.shuffle does not return anything. It modifies the input list.
import random
day=list(range(1,29))
print(day)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]
day=day[3:29]
print(day)
# [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]
shuffleday=random.shuffle(day)
print(shuffleday)
# None
print(day)
# [27, 9, 14, 15, 7, 17, 28, 10, 23, 21, 16, 12, 6, 11, 22, 25, 24, 20, 5, 19, 13, 4, 18, 8, 26]
CodePudding user response:
random.shuffle
modifies day
. It does not return anything.
This is per convention in Python, where functions which modify the arguments given to them return None
.
If you wish to generate a new list shuffled, without modifying the original, you may wish to use random.sample
.
from random import *
day = list(range(1, 29))
shuffleday = sample(day[3:29], len(day2))
print(shuffleday)
If you simply wish to get a random element from a list, you can use random.choice
.
from random import *
day = list(range(1, 29))
randomday = choice(day[3:29])
print(randomday)
CodePudding user response:
The value of shuffleday
is None
because the shuffle
function does not return a new list, it just changes the order of the elements in the list supplied as an argument.
CodePudding user response:
in fact the shuffle
function does not return anything, it shuffles the elements in place (in day
for your case).
try print(day)
instead
CodePudding user response:
random.shuffle
modifies the list in place, it doesn't return a value. so you can just replace your second last line with
shuffle(day)
then simply print shuffle without making your new variable.
Additionally I would say it's better practice to just import what you need from random
, rather than doing a *
import and cluttering your namespace (especially considering you are new to the language and unlikely to know the name of every function in the random library). In this case you can do:
from random import shuffle
CodePudding user response:
To get a random number from day list use choice
instead of shuffle
, it will return a value of random element from day[3:29]
:
from random import *
day = list(range(1, 29))
day = day[3:29]
shuffleday = choice(day)
print(shuffleday)
CodePudding user response:
This will return a value of random number. Choose one:
shuffleday = choice(range(3,29))
or
shuffleday = randint(3,29)
or
shuffleday = randrange(3,29)