rabid logic http://rabidlogic.posterous.com Most recent posts at rabid logic posterous.com Mon, 05 Sep 2011 04:50:22 -0700 Removing list elements by looping http://rabidlogic.posterous.com/removing-list-elements-by-looping http://rabidlogic.posterous.com/removing-list-elements-by-looping
While looping through a list - list index nos. 0- n are used to iterate through the list items

parent = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
child = ['a', 'b', 'c', 'd']

child index nos.
a = 0
b = 1
c=  2
d = 3

If there is a need to remove items from one list based on those present in another (parent) - logically it would require iterating through the child list and removing those items that exist in the parent list

so the foll code should do the trick..

parent = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
child = ['a', 'b', 'c', 'd']

for c in child:
 if c in parent:
  child.remove(c)

however if you print child it will output [b,d]

The reason is that python resets the index nos. of the list after the removal of an item. 
So in effect after 'a' (index 0) is removed from the child list - 'b' is set as index 0. The next loop by will pass index 1 which is now 'c'. As a consequence 'b' never enters the loop and therefore not checked if it exists in the parent list and hence not removed.

Solution:
Instead of using the actual list in the for loop, iterate through a copy of the list using [:] and carry out the removal from the original list.

parent = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
child = ['a', 'b', 'c', 'd']

for c in child[:]:
 if c in parent:
  child.remove(c)

now when you print child the output is as expected an empty list []

Permalink | Leave a comment  »

]]>
http://files.posterous.com/user_profile_pics/1366009/profile.jpg http://posterous.com/users/hckDrl2zzsesq Fabio Carvalho fabs Fabio Carvalho