[Tutor] a question about list

Terry Carroll carroll at tjc.com
Fri Nov 12 00:17:14 CET 2004


On Fri, 12 Nov 2004, Lin Jin wrote:

> i am new to python.i have a question about list.if i have two list:
> a=[a,b,c,d,e,f,g]
> b=[1,2,4]
> and i want to remove the element of a using b,that is i want a=[a,d,f,g],my 
> code is like this:
> >>>for i in b:
> >>>    del a[b]

That del statement was supposed to be "del a[i]", right?

Anyway, you're forgetting that every time you delete an entry in the list, 
every subsequent entry's position will be one less.

For example, on the first run-through, a = [A, B, C, D, E, F, G]  (I'm 
avoiding the oddity of a being used to represent both the list and the 
member of the list; I assume that was an oversight in constructing your 
post.

First iteration is del a[1], leaving a as [A, C, D, E, F, G]

Second iteration is del a[2].  But now, element 2 is D, not the C you 
wanted deleted, leaving a = [A, C, E, F, G]

Third iteration is del a[3].  Element 3 is F, leaaving a = [A, C, E, G].

A kludge would be to delete in right-to-left order instead:

 b_rev = b
 b_rev.sort()      # b = [1, 2, 4] ; sorted just to be sure
 b_rev.reverse()   # b = [4, 2, 1]
 for i in b_rev:
   del a[i]

But that's pretty ugly.  I'll bet someone has responded with a far more 
pythonic way of doing this as I've been typing.



More information about the Tutor mailing list