I've got a list which I want to print in random order. Here is the code I've written so far:
import random
words=["python","java","constant","immutable"]
for i in words:
print(i, end=" ")
input("") #stops window closing
I've tried a variety of things to print them out randomly, such as making a variable which selects only one of them randomly and then deleting the randomly. I would then repeat this step until they are all deleted and within another variable. Then I would put the variables in a list then print them out. This kept on generating errors though. Is there another way this can be done?
If you really want to, you could use
random.randint
to pick a random integer, then print the word that corresponds with that integer.hope it helps, random.choice() returns randomly chosen element from the list.
Use
random.shuffle()
to shuffle a list, in-place:Demo:
If you wanted to preserve
words
(maintain the order), you can usesorted()
with a random key to return a new randomized list:This leaves
words
unaltered:Try this:
Notice that I copied the original list first, in case you want to preserve it. If you don't mind shuffling it, this should do the trick: