Isaiah Harshbarger Isaiah Harshbarger - 2 years ago 52
Python Question

Learning Python; don't know why my function works improperly

I'm using the codeacademy python beginner's course. I'm supposed to define a function that takes a string and returns it without vowels. My function removes some vowels, but usually not all, varying with the specific string and without a clear pattern. My code's below, please look over it to see if you're able to find my error:

def anti_vowel(text):
a = len(text)
b = 0
letters = []
while a > 0:
a -= 1
b += 1
for item in letters:
if item in "aeiouAEIOU":
final = ""
return final.join(letters)

Answer Source

The issue you have is that you're iterating over your list letters and modifying it at the same time. This causes the iteration to skip certain letters in the input without checking them.

For instance, if your text string was 'aex', the letters list would become ['a', 'e', 'x']. When you iterate over it, item would be 'a' on the first pass, and letters.remove('a') would get called. That would change letters to ['e', 'x']. But list iteration works by index, so the next pass through the loop would not have item set to 'e', but instead to the item in the next index, 'x', which wouldn't get removed since it's not a vowel.

To make the code work, you need to change its logic. Either iterate over a copy of the list, iterate in reverse, or create a new list with the desired items rather than removing the undesired ones.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download