3

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?

4 Answers 4

4

Use random.shuffle() to shuffle a list, in-place:

import random

words = ["python", "java", "constant", "immutable"]
random.shuffle(words)
print(*words)

input('')

Demo:

>>> import random
>>> words = ["python", "java", "constant", "immutable"]
>>> random.shuffle(words)
>>> words
['python', 'java', 'constant', 'immutable']

If you wanted to preserve words (maintain the order), you can use sorted() with a random key to return a new randomized list:

words = ["python", "java", "constant", "immutable"]
print(*sorted(words, key=lambda k: random.random()))

This leaves words unaltered:

>>> words = ["python", "java", "constant", "immutable"]
>>> sorted(words, key=lambda k: random.random())
['immutable', 'java', 'constant', 'python']
>>> words
['python', 'java', 'constant', 'immutable']
Sign up to request clarification or add additional context in comments.

1 Comment

Nice, I like that technique of providing random.random() as key.
1

Try this:

import random
words2 = words[::]
random.shuffle(words2)
for w in words2:
    print(w, end=" ")

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:

import random
random.shuffle(words)
for w in words:
    print(w, end=" ")

Comments

0
import random
random.choice([1,2,3])
#random element from the iterable 

hope it helps, random.choice() returns randomly chosen element from the list.

3 Comments

I think the op wants a list of elements which are randomly arranged, instead of getting a random element from list.
I don't know he says he want to print them in random order, doesn't he?
yeah, like ['a','b','c'] gives ['b', 'a', 'c'], not a single character say b. But your code will only retrieve a single element, I suppose?
-1

If you really want to, you could use random.randint to pick a random integer, then print the word that corresponds with that integer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.