understanding "item for item in list_a if ..." PYTHON
python
Solution
It might be clearer if you split it into three parts:
- Take `item`;
- From `for item in list`;
- Where `item not in list_b`.
The reason the list comprehension syntax is like this is firstly because that reflects the expanded version:
for item in list: # 2.
if item not in list_b: # 3.
new_list.append(item) # 1.
and also because you don't necessarily want just `item`, for example:
new = [x ** 2 for x in old if not x % 2]
will create a `new` list with the squares of all even numbers in `old`.
Problem
I've seen the following code many times, and I know it's the solution to my problems, but I'm really struggling to 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 for some reason, I just don't understand how that first `item` fits into the equation, other than "because" (which just isn't a helpful answer), 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. it's so much easier for me to use these tools when I understand how they work, and this ones baffled me for a while. Thanks in advance.