I just read a post here about how to filter values from two lists.python: How to remove values from 2 lists based on what's in 1 list
I tried to write some code myself using for and zip, but the result is wrong, can anyone help me understand this?
xVar = [1, 2, 3, 4, 5, 6, 7]
yVar = [11, 22, 33, 44, 55, 66, 77]
z = zip(xVar, yVar)
zFiltered = [(x, y) for x, y in z if y < 50]
print zFiltered # Correct, prints [(1, 11), (2, 22), (3, 33), (4, 44)]
for (x, y) in z:
if y > 50:
z.remove((x, y))
print z # Wrong, prints [(1, 11), (2, 22), (3, 33), (4, 44), (6, 66)]
Why is this happening? I tried to use pdb and found that after z.remove((5, 55)), (x, y)'s value is (7, 77), (6, 66) is skiped, I assume that for is assigning (x, y) via indexs, removing (5, 55) will violate the original index, if so, how can I do the same thing here with for statements? and is there any other pitfalls here?