1

I'm doing an assignment for school. I'm supposed to let the user make a list of ten words, and then I'm supposed to remove all the items in the list that start with a letter chosen by the user.

This is how I tried to do it, but it doesn't remove all the words that start with the letter.
I've troubleshooted as much as I'm able to with my limited knowledge, and It looks like the for loop just isn't going through all the words.

ordalisti = []
for i in range(10):
    wordlist.append(str(input("Type a word: ").lower()))
letter = input("Choose a letter: ").lower()
for word in wordlist:
    if word[0] == letter:
        wordlist.remove(word)
print(wordlist)
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96

4 Answers4

2

Removing items from a list as you're iterating over it doesn't work. The act of removal interferes with the iteration sequence and it ends up skipping some items.

One way around this is to copy the items you want to save into a new list, and then replace the old list with the new list.

Take a look at the answers to this existing question for lots of ways to handle removing items from a list.

Community
  • 1
  • 1
John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • 1
    For minimal change, you could just do `for word in wordlist.copy()` – brianpck Nov 02 '16 at 17:29
  • Thanks! I ended up adding the items which didn't start with the chosen letter, to a new list, and then replacing the old list with the new one, like you said. – Kormakur Atli Nov 03 '16 at 21:49
2

You could use list comprehension:

print [word for word in wordlist if word[0] != letter]
Falk Schuetzenmeister
  • 1,497
  • 1
  • 16
  • 35
-1
wordlist = []

for i in range(10):
    wordlist.append(input("Type a word: ").lower().strip())

letter = input("Choose a letter: ").lower().strip()

new_wordlist = [word for word in wordlist if not word.startswith(letter)]

print(new_wordlist)
Dalvenjia
  • 1,953
  • 1
  • 12
  • 16
-2

I think instead of ordalisti = [] you need wordlist = []. And your indentation is a bit off, beginning with that first variable declaration.

rumski20
  • 361
  • 4
  • 13