understanding item for item in list_a if ... PYTHON

2024/11/17 14:18:25

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.

Answer

It might be clearer if you split it into three parts:

  1. Take item;
  2. From for item in list;
  3. 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.

https://en.xdnf.cn/q/71180.html

Related Q&A

Django redirect to custom URL

From my Django app, how to I redirect a user to somescheme://someurl.com?To give you some context in case it helps, I have a working oauth2 server written in Python/Django and I need to allow users to…

Python embedding with threads -- avoiding deadlocks?

Is there any way to embed python, allow callbacks from python to C++, allowing the Pythhon code to spawn threads, and avoiding deadlocks?The problem is this:To call into Python, I need to hold the GIL…

RuntimeError: Event loop is closed when using pytest-asyncio to test FastAPI routes

I received the errorRuntimeError: Event loop is closedeach time I try to make more than one async call inside my test. I already tried to use all other suggestions from other Stack Overflow posts to re…

Adjust threshold cros_val_score sklearn

There is a way to set the threshold cross_val_score sklearn?Ive trained a model, then I adjust the threshold to 0.22. The model in the following below :# Try with Threshold pred_proba = LGBM_Model.pre…

Efficiently insert multiple elements in a list (or another data structure) keeping their order

I have a list of items that should be inserted in a list-like data structure one after the other, and I have the indexes at which each item should be inserted. For example: items = [itemX, itemY, itemZ…

matplotlib versions =3 does not include a find()

I am running a very simple Python script: from tftb.generators import amgauss, fmlinI get this error: C:\Users\Anaconda3\envs\tf_gpu\lib\site-packages\tftb-0.0.1-py3.6.egg\tftb\processing\affine.py in …

How to fix Field defines a relation with the model auth.User, which has been swapped out

I am trying to change my user model to a custom one. I do not mind dropping my database and just using a new one, but when I try it to run makemigrations i get this errorbookings.Session.session_client…

Generate and parse Python code from C# application

I need to generate Python code to be more specific IronPyton. I also need to be able to parse the code and to load it into AST. I just started looking at some tools. I played with "Oslo" and …

An efficient way to calculate the mean of each column or row of non-zero elements

I have a numpy array for ratings given by users on movies. The rating is between 1 and 5, while 0 means that a user does not rate on a movie. I want to calculate the average rating of each movie, and t…

Selecting unique observations in a pandas data frame

I have a pandas data frame with a column uniqueid. I would like to remove all duplicates from the data frame based on this column, such that all remaining observations are unique.