[Python] Understanding "item for item in list_a if ..."

Discussão em 'Python' iniciado por Stack, Setembro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I've seen the following code many times, and I know it's the solution to my problems, but I don't understand how it works. The code in particular is:

    item for item in list_a if item not in list_b.


    For example, with for each in list, I can understand that it is going through the list, and doing a loop for each item in that list. with while x < 10 is easy to comprehend, and most other loops and similar commands are pretty straightforward. Even the for item in list_a if item not in list_b makes sense to me, though that alone doesn't seem to work without that first item... But I don't understand how that first item fits into the equation, what it represents.

    Would someone be able to help me sort this out, or be able to expand this equation out into several equations that might help me wrap my head around how it's working?

    Continue reading...

Compartilhe esta Página