1

I am trying to remove multiple strings from a list without the letter "a".

I have tried to use a function to remove every word without the letter "a" in my list

myList = ['advertisement', 'start', 'clever', 'billowy', 'melted', 'charge', 'longing', 'disgusting', 'phobic', 'carry', 'chew', 'big', 'mist', 'warn', 'faint']

def new_list(myList):
    for word in myList:
        if 'a' not in word:
            myList.remove(word)
    return myList

print(new_list(myList))

>>> ['advertisement', 'start', 'billowy', 'charge', 'disgusting', 'carry', 'big', 'warn', 'faint']

I expected it to remove all words without the letter "a" in it, but it is still outputting the words "billowy", "disgusting" and "big".

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • Possible duplicate of [Removing from a list while iterating over it](https://stackoverflow.com/questions/6500888/removing-from-a-list-while-iterating-over-it) – Aran-Fey Apr 07 '19 at 08:24

4 Answers4

1

You're trying to change the list at the same time as modifying it. Try creating a new list with the filtered objects instead.

mylist = [x for x in mylist if 'a' in x]

See more methods here: How to remove items from a list while iterating?

Sandeep Polamuri
  • 609
  • 4
  • 10
rdas
  • 20,604
  • 6
  • 33
  • 46
1

Personally, I think, Best practice is creating new list and returning it, than removing elements from existing list. so,

def new_list(myList):
    newlist = []
    for word in myList:
        if 'a' in word:
            newlist.append(word)
    return newlist
Priya
  • 36
  • 2
0

You can do it by initializing new list in your function.

myList = ['advertisement', 'start', 'clever', 'billowy', 'melted', 'charge', 'longing', 'disgusting', 'phobic', 'carry', 'chew', 'big', 'mist', 'warn', 'faint']

def new_list(myList):
    l = []
    for word in myList:
        if 'a' in word:
            l.append(word)
    return l

print(new_list(myList))
Phoenix404
  • 898
  • 1
  • 14
  • 29
0

You cannot modify a list you are currently iterating, try making another copy of the list. Try using slice operator to make a copy of the list.

for word in myList[:]:
    if 'a' not in word:
        myList.remove(word)
return myList
Sandeep Polamuri
  • 609
  • 4
  • 10