0

I have a list of Windows paths:

pathsList = ['...', '...', '...', ...]

I need to exclude the paths that contain a substring (name of a folder).

substring = "folderName"

I've tried something like this:

for item in pathsList :
    if substring in item:
        pathsList.remove(item)

It kinda worked for, like 2 or 3 elements of the list. It didn't search all the elements of the list. Can anyone help me understand why or find another solution? I've searched a lot and tried many solutions here on StackOverflow but nothing worked for me. I must be doing something wrong for this code to work only for a couple of items.

Catarina Ribeiro
  • 562
  • 2
  • 16
  • 2
    `pathsList = [item for item in pathsList if substring not in item]` – Barmar May 12 '22 at 17:52
  • It worked, thanks... I've tried a lot of things and got strange results, but this worked just fine! Thank you so much – Catarina Ribeiro May 12 '22 at 17:55
  • modifying a list you're iterating over lead to weird result, is better to make a new one with the desire items – Copperfield May 12 '22 at 17:59
  • @CatarinaRibeiro read the linked duplicate (at the top), the accepted answer has a pretty clear explanation of what is going on, but essentially, when you remove an item from a list, it will skip the next item in the iteration because the indices shift – juanpa.arrivillaga May 12 '22 at 18:15

0 Answers0