list_a-list_b

Gerhard =?unknown-8bit?Q?H=E4ring?= gerhard at bigfoot.de
Tue Apr 16 20:44:38 EDT 2002


* John <nobody at nobody.com> [2002-04-16 19:30 -0500]:
> 
> Hi, I need a help in writing a function that does
> 
> list_a=[1,2,4], list_b=[2,4]
> list_minus(list_a,list_b)
> print list_a #will print out a=[1] after removing all elements ([2,4])
> appearing in list_b

Ok.

>>> l1 = [3,4,5,6]
>>> l2 = [4,5]

Do you still need the original list? If yes, you'd better make a copy of
it:

>>> l3 = l1[:]

Then remove all elements of l2 in l3 like this:

>>> for item in l2:
...     l3.remove(item)
>>> l3
[3, 6]

To fully understand what's going on here, you can read in the
documentation about lists. The distinction about mutable/immutable
objects comes into play here, too: lists are mutable => you change them
"in-place". That's also the reason why l3 = l1[:] creates a copy, but
l3 = l1 would not.

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))





More information about the Python-list mailing list