Reputation: 14548
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.
Upvotes: 4
Views: 1564
Reputation: 287775
Instead of removing elements you don't like, you should simply use filter
:
x1 = filter(x1, lambda x: x not in y1)
Alternatively, a list comprehension works as well:
x1 = [x for x in x1 if x not in y1]
If y1 is very large, you should look up in a set, like this:
y1set = set(y1)
x1 = filter(x1, lambda x: x not in y1set)
For reference, pop
takes an index, and the generic way to get an index is enumerate
. However, in nearly all cases, there's a shorter and cleaner way to write the code than using indices.
Upvotes: 2
Reputation: 362557
The general way to do this is with enumerate
.
for idx, item in enumerate(iterable):
pass
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:
xl = [item for item in xl if item not in yl]
Upvotes: 8
Reputation: 2609
How about xl = [x for x in xl if x not in y]
This is known as a list comprehension.
Upvotes: 4