while i’m interating a list, how can i get the id of the current item to reference it to list methods?
xl = [1,2,3] # initial list
yl = [3,2] # list used to remove items from initial list
for x in xl[:]:
for y in yl:
if x == y:
xl.pop(x) # problem
break
print x, y
print xl
in the simple example, i want to loop through the 2 lists, and when i find a similar item, remove it from list 1.
What should i use instead of X in the line commented with “#problem”?
PS: Note it’s a copy i’m iterating from.
The general way to do this is with
enumerate.But for your use case, this is not very pythonic way to do what you seem to be trying. Iterating over a list and modifying it at the same time should be avoided. Just use a list comprehension: