HELP PLEASE printing single characters!

John Strick jstrickler at gmail.com
Wed Dec 2 19:08:24 EST 2015


On Wednesday, December 2, 2015 at 12:58:30 PM UTC-6, Dylan Riley wrote:
> hi all,
> I have been trying to figure out all day why my code is printing single characters from my list when i print random elements using random.choice the elements in the list are not single characters for example when i print, print(LIST[random.choice]) i get:
> ["e", "x", "a", "m", "p", "l", "e"] when i should get ["example"].
> 
> my code is:
> #Create a program that prints a list of words in random order.
> #The program should print all the words and not repeat any.
> 
> import random
> 
> LIST = ["blue ", "red ", "yellow ", "green ", "orange "]
> order = []
> 
> print("This game will print a random order of colours")
> print("The list is", LIST)
> input("press enter to start")
> 
> 
> 
> while LIST != []:
>     choice = random.choice(LIST)
>     order += choice
>     while choice in LIST:
>         LIST.remove(choice)
> print(order)
>         
>     
>     
> input("press enter to exit")
> 
> thanks in advance guys

You could just shuffle the list first, then loop through it. This will guarantee that each color is only used once. 

    import random
    LIST = ["blue ", "red ", "yellow ", "green ", "orange "]
    random.shuffle(LIST)
    for color in LIST:
        print(color)
        # or add to order or whatever you need to

   



More information about the Python-list mailing list