filter a list of strings

Sivan Greenberg sivan at vitakka.co
Wed Dec 9 09:35:23 EST 2015


That might also work:

new_list = [i for i in the_list if i not in targets]
# given you have no special requirements for the selection
# out of 'targets'

-Sivan

On Wed, Dec 9, 2015 at 12:58 AM, Thomas 'PointedEars' Lahn <
PointedEars at web.de> wrote:

> Mark Lawrence wrote:
>
> > On 03/12/2015 01:15, c.buhtz at posteo.jp wrote:
> >> I would like to know how this could be done more elegant/pythonic.
> >>
> >> I have a big list (over 10.000 items) with strings (each 100 to 300
> >> chars long) and want to filter them.
> >>
> >> list = .....
> >> […]
> >
> > targets = ['Banana', 'Car'...]
> > for item in list[:]:
> >      for target in targets:
> >          if target in item:
> >              list.remove(item)
> >
> >> btw: Is it correct to iterate over a copy (list[:]) of that string list
> >> and not the original one?
> >
> > Absolutely :)
>
> However, “list” is a built-in class/constructor that would be overwritten
> this way.  One should choose another identifier than “list” for one’s
> variables.
>
> --
> PointedEars
>
> Twitter: @PointedEars2
> Please do not cc me. / Bitte keine Kopien per E-Mail.
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Sivan Greenberg
Co founder & CTO
Vitakka Consulting



More information about the Python-list mailing list