0

I'm trying to iterate over list with items. When the item is processed I want to delete the item and write the list into the file. But there is a problem that only items on even positions are deleted.

Here is a very simple example:

>>> x = [1,2,3,4,5,6,7,8,9]
>>> for i in x:
...     print x
...     x.remove(i)
...     write_x_into_the_file()
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 5, 6, 7, 8, 9]
[2, 4, 6, 7, 8, 9]
[2, 4, 6, 8, 9]

I think that it is because it iterates using index incrementation. Do you know some pythonic workaround?

Milano
  • 18,048
  • 37
  • 153
  • 353
  • What are you *actually trying to achieve?* – jonrsharpe Sep 08 '15 at 15:50
  • Those items are urls in real. I want to do some things with all of those urls (to get some data). But sometimes, there are situations when connection fell or similar problems. To be able to continue from the url where the problem raised, I have to saving them into the file. – Milano Sep 08 '15 at 15:52
  • So why does that entail removing the items from the list while you're iterating over it? – jonrsharpe Sep 08 '15 at 15:55
  • The first thing is to find all urls. Those urls are written into the file. The next step is to process each of these urls so the urls are loaded and processed one by one. When url is processed, it is removed from the list because I don't want process it twice and the list is saved so the script knows where to start from if there was some problem with connection. – Milano Sep 08 '15 at 16:03
  • Does order matter? Could you just `pop` each one? – jonrsharpe Sep 08 '15 at 16:04
  • It would be much better if the order was maintained. Yes, I'm trying to keep the order. It seems that I should use two lists, but I was looking for more elegant option. – Milano Sep 08 '15 at 16:11
  • `while x: process(x.pop(0))` – jonrsharpe Sep 08 '15 at 16:13
  • if you want to keep order with a loop, use a deque and popleft – Padraic Cunningham Sep 08 '15 at 18:02

2 Answers2

0
x = [1,2,3,4,5,6,7,8,9][::-1]
while len(x):
    ele = x.pop() # equv to ordinary for loop

x = [1,2,3,4,5,6,7,8,9]
while len(x):
    ele = x.pop() # reversed loop
taesu
  • 4,482
  • 4
  • 23
  • 41
-1

You could keep track of all indexes that need to be deleted and just remove them after

delete = []
my_list = [1,2,3,4,5,6,7,8,9]
for i, x in enumerate(my_list):
    write_x_into_the_file()
    delete.append(i)

for d in delete:
    del my_list[d]
Cody Bouche
  • 945
  • 5
  • 10