Jump to content

Why isit not deleting from the list?

- - - - -

  • Please log in to reply
3 replies to this topic

#1
synk

synk

    Newbie

  • Members
  • PipPip
  • 18 posts

#print out words in a random order

import random


word = ["blue", "red", "yellow"]

random = random.choice(word)



if random == "blue":

    print "blue"

    del word[0]

    print random

elif random =="red":

    print "red"

    del word[1]

else:

    print "yellow"

    del word[2]

    print word

        


raw_input("press")


"Create a program that prints a list of words in random order. The program should print all the words and not repeat any."

Any help?

#2
restored

restored

    Newbie

  • Members
  • PipPip
  • 14 posts

# -*- encoding: utf-8 -*-


#print out words in a random order

import random


word = ["blue", "red", "yellow"]

while word:

    r = random.choice(word)

    print r

    word.remove(r)

    

raw_input("press...\n")



synk said:

The program should print all the words and not repeat any.
.remove() removes only one item, so you have to do a loop, otherwise you will get equal items if the list is word = ["blue", "red", "yellow", "red"]

#3
synk

synk

    Newbie

  • Members
  • PipPip
  • 18 posts
Thanks, so where would i use the del function?

#4
restored

restored

    Newbie

  • Members
  • PipPip
  • 14 posts
you see remove() already deletes them


# -*- encoding: utf-8 -*-


#print out words in a random order

import random


word = ["blue", "red", "yellow", "red"]

while word:

    r = random.choice(word)

    print r

    while r in word:

        word.remove(r)

    

raw_input("press...\n")


now without duplicates


[guest@localhost tests]$ python t2.py

red

yellow

blue

press...


[guest@localhost tests]$


Edited by restored, 18 February 2011 - 10:53 PM.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users