filter a list of strings

Chris Angelico rosuav at gmail.com
Thu Dec 3 04:40:51 EST 2015


On Thu, Dec 3, 2015 at 8:27 PM,  <c.buhtz at posteo.jp> wrote:
> Thank you for your suggestion. This will help a lot.
>
> On 2015-12-03 08:32 Jussi Piitulainen <harvesting at is.invalid> wrote:
>> list = [ item for item in list
>>          if ( 'Banana' not in item and
>>               'Car' not in item ) ]
>
> I often saw constructions like this
>   x for x in y if ...
> But I don't understand that combination of the Python keywords (for,
> in, if) I allready know. It is to complex to imagine what there really
> happen.
>
> I understand this
>   for x in y:
>     if ...
>
> But what is about the 'x' in front of all that?

It's called a *list comprehension*. The code Jussi posted is broadly
equivalent to this:

list = []
for item in list:
    if ( 'Banana' not in item and
            'Car' not in item ):
        list.append(item)

I recently came across this blog post, which visualizes comprehensions
fairly well.

http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/

The bit at the beginning (before the first 'for') goes inside a
list.append(...) call, and then everything else is basically the same.

ChrisA



More information about the Python-list mailing list