1

I just started learning Python and I want to learn how to remove duplicate vowels in my input in a list (I am also sorry for my poor English skills).

so here's my code:

vowels = ['a', 'e', 'i', 'o', 'u']
word = input("Provide a word to search for vowel >> ")
found = []

for letter in word:
    if letter in vowels:
        found.append(letter)

for letter in found:
    if found.count(letter) > 1:
        found.remove(letter)

print(found)

If I typed, let's say, "aaaaa", the output is:

['a', 'a']

where it should only print:

['a']

how do I fix this code?

P.S. this is my first post in stackoverflow and I'd really appreciate anyone who tried to reach out. Thank you so much!

Jeco
  • 13
  • 3

2 Answers2

1

You are trying to modify the list while iterating over it. This answer has detailed explanation on this.

As a solution, consider using another list for unique elements like this:

vowels = ['a', 'e', 'i', 'o', 'u']
word = input("Provide a word to search for vowel >> ")
found = []
found_unique = []

for letter in word:
    if letter in vowels:
        found.append(letter)

[found_unique.append(x) for x in found if x not in found_unique]

print(found_unique)

But the simplest approach would be using python3's set() as its elements are unique by definition.

nkrivenko
  • 1,231
  • 3
  • 14
  • 23
1

Either use a set or simply remove the letter from list of things you look for after you found it the first time:

vowels = ['a', 'e', 'i', 'o', 'u']
word = input("Provide a word to search for vowel >> ")
found = []

for letter in word:
    if letter in vowels:
        found.append(letter)
        vowels.remove(letter)  # no longer look for this specific vowel
    if not vowels: 
        break                  # no more vowels to look for, quick exit

print(found)

Output:

Provide a word to search for vowel >>  aaaaa
['a']
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69