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:
It might be clearer if you split it into three parts:
item
;for item in list
;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
.