remove a list from a list
Tim Chase
python.list at tim.thechases.com
Fri Nov 17 13:32:38 EST 2006
> I have a list like
> e = ['a', 'b', 'e']
> and another list like
> l = ['A', 'a', 'c', 'D', 'E']
> I would like to remove from l all the elements that appear in e
> case-insensitive. That is, the result would be
> r = ['c', 'D']
>
> What is a *nice* way of doing it?
Well, it's usually advantageous (for speed purposes) to make a
set out of your lookup data. One can then use it for a list
comprehension something like
>>> e = ['a', 'b', 'e']
>>> l = ['A', 'a', 'c', 'D', 'E']
>>> s = set(e)
>>> [x for x in l if x.lower() not in s]
['c', 'D']
This presumes that "e" is all lowercase letters. Otherwise, you
can force it with
s = set(c.lower() for c in e)
-tkc
More information about the Python-list
mailing list