-1

Write a function removeLetter(word, letter) that takes in a word and a letter as arguments and remove all the occurrence of that particular letter from the word. The function will returns the remaining leters in the word. Here is my first version

 def removeLetter(word, letter):
     word=list(word)
     for x in word :

      if x==letter:
       word.remove(x)

     return "".join(str(x) for x in word)
    print( removeLetter("apple", "p"))

if i use another variable for word for example word1 it works perfectly but what is the reason ?

def removeLetter(word, letter):
 word1=list(word)
 for x in word :

  if x==letter:
   word1.remove(x)

 return "".join(str(x) for x in word1)
print( removeLetter("applepie", "p"))

2 Answers2

0

You are trying to iterate down a list while removing its elements. My guess is that it's moving down the list according to index number. Hence, it will skip the subsequent element as you shorten the list. You can see this phenomenon by using print statements.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
A.H
  • 85
  • 8
0

First off, a string is simply a list of characters so the statement word1 = list(word) is unnecessary in your code.Python strings are also immutable and that is probably why your first solution doesn't work In other news, your problem could simply be solved with:

def remove_letters(word,letter):
    return word.replace(letter,'')

It's python, you don't need to overthink stuff :)

silverhash
  • 880
  • 8
  • 21