[Tutor] Lists and While Loops

James Reynolds eire1130 at gmail.com
Wed Mar 28 22:23:19 CEST 2012

On Wed, Mar 28, 2012 at 2:53 PM, Ricky Brown <rjbrow2 at gmail.com> wrote:

> So I have to write a program that reads a message from the user and prints
> a new message that contains all the words from the original message but in
> the same order without repeating any of them unless they show up more than
> once in the original message.
> What I have thus far looks like this:
> message = input("Your message:")
> myList = message.split()
> y = random.choice(myList)
> z = len(myList)
> while z !=0:
>     myList.remove(y)
>     print(y)
> I can't figure out
> 1) How to remove "y" from the list and continue the loop; when I use
> .remove etc. it runs once then give me the error that "y" is not in the
> list.
> I imagine the answer is quite simple I'm just getting really frustrated
> trying to get this done any advice is appreciated.
> Thanks
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

You have two main issues, one, you are not designing the program to do what
is specified in the directions, and two, the program you did write has a
few things that you need to work on. For the later portion, I've provided
some commentary below in the body of your code that I have copied over.

message = input("Your message:")
myList = message.split()
y = random.choice(myList)

#here you have saved some random choice from your list to the variable y.

z = len(myList)

#Here you save the length of the list to the variable z.

while z !=0:
    #the above says, keep doing this loop while z is not equal to 0.
    #Here you remove an item from the list, the item stored to the variable
y from above.
    #it's important to note that this does not change the value of z and
this does not change the value of y.
    #y gets printed once

The loop then goes back up and since z has not changed (and in fact never
will change, because you have never told it to change) the while loop runs
through another iteration.

However, once myList.remove(y) is evaluated again for the second time it
throws an error because y is no longer in the list.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120328/569226ae/attachment.html>

More information about the Tutor mailing list