Skip to content Skip to sidebar Skip to footer

Python For Loop Skipping Every Other Value

I have run into an odd problem in my django application where a for loop is skipping every other item. I have take a returned queryset and list()ed to iterate over. The point of do

Solution 1:

temp and items refer to the same object, so when you do items.remove() you're also modifying temp. You probably want to do temp = items[:] to copy the values of the items list.

Solution 2:

You should not be modifying a data structure while iterating over it.

Anyways, this is a more concise and performant code to do your operation:

items = list(listobj.getItems())
rendered = set((int(i) for i in request.POST['rendered'].split(',')))
unrendered = [item for item in items if item.id not in rendered]

Post a Comment for "Python For Loop Skipping Every Other Value"