-3

The code raises an AttributeError when run.

letters = ['a', 'b', 'c', 'a']

for letter in letters:
  letter.remove('a')
  print(letter)
Flair
  • 2,123
  • 1
  • 24
  • 39
  • 2
    `letter` is a string, not a list, so has no `remove` attribute – Nick Apr 24 '22 at 08:29
  • It's really not clear what you're trying to achieve here... – Nick Apr 24 '22 at 08:29
  • In complement to the duplicate, you can have a look at https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it to see why your approach (removing while iterating) causes problems. – Thierry Lathuille Apr 24 '22 at 08:33
  • Does this answer your question? https://stackoverflow.com/questions/2793324/is-there-a-simple-way-to-delete-a-list-element-by-value – Abhyuday Vaish Apr 24 '22 at 08:33

1 Answers1

0

You have to use the remove() method on the list, not on its items. You should therefore use list.remove(item), without any for loops:

letters=['a', 'b', 'c', 'a']

letters.remove('a')

In reaction to your comment, here is a script to remove all occurences in a list:

while 'a' in letters:
    letters.remove('a')

The following code is more like your code. I think that this is what you intended to do.

for letter in letters.copy():
    if letter=='a':
        letters.remove('a')

Note: Due to how for loops work in python, we need to make a temporary copy of the list. Otherwise certain items will be skipped.

The_spider
  • 455
  • 2
  • 9