0

So I have a string task where I'm supposed to remove the vowels from the input string.

case = list(input().lower()) 
vowels = ["a","e","i","o","u","y"]

for i in case:
    for k in vowels:
        if i == k:
            ind = case.index(i)
            del case[ind]
print(case)

Say my input is the word

'Tour'

instead of deleting vowels 'o' 'u' and printing

['t','r']

it prints

['t','u','r']

instead.

However, if I run the for statement separately through jupyter notebook, it can give me ['t','r'] but it's not supposed to run twice.

Any advice please.

mathn00b
  • 57
  • 1
  • 6
  • 2
    Do not modify a list you are iterating over... construct a new list (you can look into list comprehensions if you want to use python's more powerful constructs). (And since when is `y` a vowel :). – AChampion Aug 12 '18 at 23:16

1 Answers1

3

The problem is that you are changing the list of the outer for loop. E. g. your word is "Tour". In your for loop i is set to the first letter of case. It's T and nothing happens. i is set to the second letter, which is vowel o. You remove it and the second letter is now u. i is set to the third letter r and nothing happens. Your program finishes.

To avoid this problem use a second list for the result and do not change the list you are iterating over.

case = list(input().lower()) 
vowels = ["a","e","i","o","u"]
result = ''

for i in case:
    if i not in vowels:
        result += i
print(result)
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
  • OK, so I understand why the 'u' was not deleted because it replaced the 'o's' index position and therefore skipped by the computer. – mathn00b Aug 13 '18 at 00:07