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:
- take
item
; - from
for item in list
; - 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
Post a Comment