0

I have an item in list that contains just a quotation mark and a comma (",) and I can't seem to pop that item from the list

I've tried

for item in my_list:
    if item == '",':
        my_list.pop(my_list.index(item))

I've also tried

for item in my_list:
    if item == '\",':
        my_list.pop(my_list.index(item))

I've gotten no luck, is there anything I'm missing

Sammy
  • 1
  • 3
  • 1
    `mylist = [x for x in mylist if x != '",']` – Unmitigated Jan 27 '23 at 16:02
  • 1
    What you're missing is that you should **never** modify an iterable whilst iterating over it. There are various ways to do this safely but reconstructing the list (as suggested by @Unmitigated) is typically optimum – DarkKnight Jan 27 '23 at 16:10
  • You have both `item1` and `item` in your code. That seems to be one problem. – Mark Jan 27 '23 at 16:10
  • Welcome to Stack Overflow. Please read [ask]. "I've gotten no luck, is there anything I'm missing" - this is extremely unhelpful. "I've gotten no luck" is not something we can help with, because a) we [don't "help with"](https://meta.stackoverflow.com/questions/284236) anything and b) it does not **describe a problem**. In the future, please make sure to explain **what happened when you tried the code**, and **how that is different** from the expected result. – Karl Knechtel Jan 27 '23 at 16:32
  • "is there anything I'm missing" is not a properly direct question; this is **not a discussion forum**, so instead try to think in terms of questions like "what is wrong with the code?" or better yet, "why does <...> happen at <...> point in the process? I expected <...> instead because ". – Karl Knechtel Jan 27 '23 at 16:32

2 Answers2

0

Your code has two issues:

  1. Typically it is frowned upon to modify an iterable while iterating over it. You can iterate over a copy of the list instead, and then modify the original list.

  2. You are trying to compare item1 to something, but item1 is not defined. You should change this to item.

Here is the modified code:

my_list = ['",', 'a', 'b', 'c']
for item in my_list.copy():
    if item == '",':
        my_list.pop(my_list.index(item))
        
print(my_list)

Output

['a', 'b', 'c']

Ryan
  • 1,081
  • 6
  • 14
  • Please read [answer] and do not attempt to answer questions that are common duplicates. We have reams of information on the site already about this problem. – Karl Knechtel Jan 27 '23 at 16:37
-1

Try the following:

element_to_remove = '",'

for _ in range(my_list.count(element_to_remove)):
    my_list.remove(element_to_remove)
JMA
  • 803
  • 4
  • 9