understanding "item for item in list_a if ..." PYTHON -


i've seen following code many times, , know it's solution problems, i'm struggling understand how works. code in particular is:

item item in list_a if item not in list_b. 

for example, for each in list, can understand going through list, , doing loop each item in list. while x < 10 easy comprehend, , other loops , similar commands pretty straightforward. for item in list_a if item not in list_b makes sense me, though alone doesn't seem work without first item...but reason, don't understand how first item fits equation, other "because" (which isn't helpful answer), represents.

would able me sort out, or able expand equation out several equations might me wrap head around how it's working. it's easier me use these tools when understand how work, , ones baffled me while.

thanks in advance.

it might clearer if split 3 parts:

  1. take item;
  2. from for item in list;
  3. where item not in list_b.

the reason list comprehension syntax firstly because reflects expanded version:

for item in list: # 2.     if item not in list_b: # 3.         new_list.append(item) # 1. 

and because don't want item, example:

new = [x ** 2 x in old if not x % 2] 

will create new list squares of numbers in old.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -