Index ¦ Archives ¦ RSS

Remove items from a python list

Estimated read time: 1 minutes

One item in Python's magic word is that you don't have to really care about memory management. I already know if i want to "strdup" a list, then i need foo[:], but I did not notice that in case I iterate over a list _and_ modify it, then I need such a trick as well.

Example

l = ['a', 'b']
for i in l:
        l.remove(i)
print l

So we remove each item from the list (an expensive version of "l = []").

However, the result will be "['b']". Now if you use "for i in l[:]:", everything will be fine, because you can iterate over the original list.

It's a shame that I do python for more than 2 years, and I did not know such a basic stuff. :(

(original post)

© Miklos Vajna. Built using Pelican. Theme by Giulio Fidente on github.