0

Not sure if I am doing anything silly here but I am trying to remove all items in a list which starts with 00:00:00. but not all items are matched.

tc = ['00:00:00.360', '00:00:00.920', '00:00:00.060', '00:00:02.600', '00:00:05.960', '00:00:01.040', '00:00:01.140', '00:00:01.060', '00:00:01.480', '00:00:00.140', '00:00:00.280', '00:00:01.200', '00:00:00.400', '00:00:01.220', '00:00:00.380']
for item in tc:
    if item.startswith(str('00:00:00.')):
        tc.remove(item)
print (tc)

Result:

['00:00:00.920', '00:00:02.600', '00:00:05.960', '00:00:01.040', '00:00:01.140', '00:00:01.060', '00:00:01.480', '00:00:00.280', '00:00:01.200', '00:00:01.220']

Expected Result:

['00:00:02.600', '00:00:05.960', '00:00:01.040', '00:00:01.140', '00:00:01.060', '00:00:01.480', '00:00:01.200', '00:00:01.220']

Any idea what could be the issue here?

srt243
  • 63
  • 6
  • 4
    Do not remove from the list during iterating over it! The iterator position changes, that's why it doesn't remove everything. – h4z3 Feb 14 '20 at 11:13
  • 2
    This answers your question: [strange result when removing item from a list](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list) – Jongware Feb 14 '20 at 11:16
  • Does this answer your question? [Looping over list and removing entries in Python](https://stackoverflow.com/questions/31558845/looping-over-list-and-removing-entries-in-python) – h4z3 Feb 14 '20 at 11:16
  • @h4z3: mine is a couple of years older. "Baffling crowds since 2011!" – Jongware Feb 14 '20 at 11:18
  • 1
    @usr2564301 I had trouble finding a good question while reporting duplicate, there are so many of them. :D – h4z3 Feb 14 '20 at 11:33

1 Answers1

8

that is because you change tc while iterating through it. you can achieve your goal with a simple list comprehension:

tc = [item for item in tc if not item.startswith('00:00:00.')]
Tal
  • 548
  • 3
  • 8
  • Or you can create a copy of the list, and delete only in that new list. The solution @Tal gave is better, but maybe 'create a copy' is easier to understand. – Wimanicesir Feb 14 '20 at 11:16
  • To understand this list enumeration, visit https://stackoverflow.com/questions/22620091/understanding-item-for-item-in-list-a-if-python – Suriya Feb 14 '20 at 11:48