list_a-list_b

Bengt Richter bokr at oz.net
Tue Apr 16 22:00:03 EDT 2002


On Wed, 17 Apr 2002 02:44:38 +0200, Gerhard =?unknown-8bit?Q?H=E4ring?= <gerhard at bigfoot.de> wrote:

>* 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.
>
If you have duplicate elements in your list, you may also want to
think about what you really want list_minus to mean, and whether
you want to preserve duplicates in the result:

 >>> a=[1,2,3,3,4,5]
 >>> a
 [1, 2, 3, 3, 4, 5]
 >>> a.remove(3)
 >>> a
 [1, 2, 3, 4, 5]

For large lists with no duplicates it may be faster to create a dictionary
from the first list and delete entries with keys from the second list.

Regards,
Bengt Richter



More information about the Python-list mailing list