How can a print elements in a list randomly in python?
Question: 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?


Answer: Use
[`random.shuffle()`](http://docs.python.org/3/library/random.html#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']
    

