filter a list of strings

Jussi Piitulainen harvesting at is.invalid
Thu Dec 3 06:53:13 EST 2015


<c.buhtz at posteo.jp> writes:

> Thank you for your suggestion. This will help a lot.
>
> On 2015-12-03 08:32 Jussi Piitulainen 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.

Others have given the crucial search word, "list comprehension".

The brackets are part of the notation. Without brackets, or grouped in
parentheses, it would be a generator expression, whose value would yield
the items on demand. Curly braces would make it a set or dict
comprehension; the latter also uses a colon.

> I understand this
>   for x in y:
>     if ...
>
> But what is about the 'x' in front of all that?

You can understand the notation as collecting the values from nested
for-loops and conditions, just like you are attempting here, together
with a fresh list that will be the result. The "x" in front can be any
expression involving the loop variables; it corresponds to a
result.append(x) inside the nested loops and conditions. Roughly:

result = []
for x in xs:
    for y in ys:
        if x != y:
            result.append((x,y))
==>

result = [(x,y) for x in xs for y in ys if x != y]

On python.org, this information seems to be in the tutorial but not in
the language reference.



More information about the Python-list mailing list