I have a file I am putting into a list and I am wanting to take some things out of it, and append to another list ( I have no problem with that), the problem I run into is removing the things out of the first list. below is what I have tried but it only removes every other from the original list.
list:
bob g1 3110
bob g2 244
bob g3 -433
greg fun112 10595
greg fun113 -1203
greg fun114 -3049.999
greg fun115 3808
greg fun116 320
greg got112 -600
greg got113 5958
greg got114 1249
file1 = open('test','rb').read().splitlines()
file1=sorted(file1)
test_group = ['fun','got']
test= []
for product in file1:
spt = product.split(",")
for line in spt:
if line[:3] in test_group:
x = test.append(product)
y = file1.remove(product)
the test [ ] list is fine all of the items I want in there go with no problem, but when I review file1 it only takes out every other one of ‘fun’ and ‘got’ lines
why is this only taking out every other one, and how do I fix it?
Don’t try to modify a list you’re iterating over! That’s not going to work!
If you make a copy of the list, then it should work: