I am trying to do a simple filtering on python arrays. I have 2 arrays:
a_array
that has full set of values of some sort of Id, and lookup
array that has subset of a_array
.
I want to keep only id that are present in my lookup
array, I am trying with pop method to remove the values from a_array
which are not present in lookup
array but it ends up with Index out of range, I understand every time a value is removed from a_array
its size gets changed hence we get index of range exception , how do I fix this problem.
a_array=[1,2,3,4,5,6,7,14,8,9,100,19,200,300,45,67,989,45,201]
loopkup = [2, 14,100,200,300]
def demo_func(a_array, loopkup):
for i in range(len(a_array)):
if a_array[i] not in loopkup:
print('poping customer id {0}-->{1}' + str(i))
a_array.pop(i)
def main():
demo_func(a_array, loopkup)
if __name__ == '__main__':
main()
Exception:
poping customer id {0}-->{1}0
poping customer id {0}-->{1}1
poping customer id {0}-->{1}2
poping customer id {0}-->{1}3
poping customer id {0}-->{1}4
poping customer id {0}-->{1}6
poping customer id {0}-->{1}8
poping customer id {0}-->{1}9
poping customer id {0}-->{1}10
Traceback (most recent call last):
File "<string>", line 15, in <module>
File "<string>", line 12, in main
File "<string>", line 6, in demo_func
IndexError: list index out of range