Masih
Masih

Reputation: 980

how does "not x" in python set method works?

im new to Python3.3 and i wanted to eliminate repetitive members from a list, i found this short code on the net , but i don't know what is the logic behind this code? ,especially the part "not seen_add(x)"!.

def f7(seq):
    seen=set()
    seen_add=seen.add
    return[x for x in seq if x not in seen and not seen_add(x)]

can someone clear this up for me?!

Upvotes: 1

Views: 505

Answers (1)

user2357112
user2357112

Reputation: 281476

The add method of a set always returns None. None is considered false in a boolean context, so not seen_add(x) is always True. and short-circuits, so seen_add(x) is only executed if x wasn't registered as seen. The seen_add(x) is to keep track of the fact that x has now been seen, not to filter anything, which is why not seen_add(x) is always true.

Turning the list comprehension into an equivalent loop, we have

def f7(seq):
    seen=set()
    seen_add=seen.add
    result = []
    for x in seq:
        if x not in seen and not seen_add(x):
            result.append(x)
    return result

Converting the and to a more readable form, and eliminating the seen_add microoptimization, the code you found is equivalent to the following:

def f7(seq):
    seen=set()
    result = []
    for x in seq:
        if x not in seen:
            seen.add(x)
            result.append(x)
    return result

Upvotes: 2

Related Questions