You wrote file = list(f)
where the usual idiom would be to assign f.readlines()
,
but that's fine.
Then you mutate a list while iterating over it.
That's a little more of a problem.
Also, using pop(0)
would be more natural than asking remove()
to
search for a value matching line
(which should be the first value encountered).
Here is a simpler example of mutating while iterating:
>>> lst = [4, 5, 6]
>>> for item in lst:
... print(lst.pop(0))
...
4
5
Popping within the loop interferes with the iteration, which is expected because
we shouldn't have been mutating during iteration in the first place.
The item
variable never takes on the value 5
.
Making a copy and iterating over that is one way out:
>>> lst = [4, 5, 6]
>>> for item in list(lst):
... print(lst.pop(0))
...
4
5
6
Perhaps you don't want to make a copy of the list.
This code looks more like Fortran than Python,
but the behavior it shows is probably closer to what you were hoping for.
>>> lst = [4, 5, 6]
>>> for i in range(len(lst)):
... print(i, lst.pop(0))
...
0 4
1 5
2 6