pHorseSpec pHorseSpec - 1 year ago 65
Python Question

Difference In List - Python - Syntax Explanation

Can someone please explain the meaning the syntax behind the following line of code:

temp3 = [x for x in temp1 if x not in s]

I understand it's for finding the differences between 2 lists, but what does the 'x' represent here? Each individual element in the list that is being compared? I understand that
are lists. Also, does
x for x
have to have the same variable or could it be
x for y

Answer Source

It iterates through each element in temp1 and checks to see if it is not in s before including it in temp3.

It is a shorter and more pythonic way of writing

temp3 = []
for item in temp1:
    if item not in s:

Where temp1 and s are the two lists you are comparing.

As for your second question, x for y will work, but probably not in the way you intend to, and certainly not in a very useful way. It will assign each item in temp1 to the variable name y, and then search for x in the scope outside of the list comprehension. Assuming x is defined previously (otherwise you will get NameError or something similar), the condition if x not in s will evaluate to the same thing for every item in temp1, which is why it’s not terribly useful. And if that condition is true, your resulting temp3 will be populated with xs; the y values are unused.

Do not take this as saying that using different variables in a list comprehension is never useful. In fact list comprehensions like [a if condition(x) else b for x in original_sequence] are often very useful. A list comprehension like [a for x in original_sequence if condition(x)] can also be useful for constructing a list containing exactly as many instances of a as the number of items in original_sequence that satisfy condition().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download