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:
First off, the line of code you're referring to is called a list comprehension. Basically, as you know, it is a way to create a list of items "on the go", with the ability for conditionals as well.
When you create a list comprehension, you are building a list, and you need to to tell Python what you are putting into that list. If a list comprehension was simply:
new = [for item in list_a if item not in list_b]
It would not be a list comprehension at all, because you are simply iterating and not storing any thing in the new list. So, in order to actually save items into the new list, you need:
new = [item for item in list_a if item not in list_b]
# for each item in 'list_a', if 'item' is not in
# 'list_b', add item to 'new'
Which is the same as:
i = 0
for item in list_a:
if item not in list_b:
new[i++] = item
Think of "that first item
" as the value you are putting into the list. Essentially a list comprehension enumerates, keeping track of the index and does something like this for each iteration:
new[index] = item