Samir Said
Samir Said

Reputation: 373

Python command working but why?

I have a simple code that goes like this in Python:

a = [1,2,3]
b = [2,4,6]

def union(a,b):
    pos = 0
    while pos < len(b):
        n = b[pos]
        if n in a is not 'True':
            a = a
        else:
            a.append(n)
        pos = pos +1
    return a

print union(a,b)

As you can see, the first IF statement makes no sense. However, if I code it this way:

if n in a is 'True':
    a.append(n)

it does not work. The first code segment changes a = [1,2,4,6] - only adding numbers from list 'b' that are not in list 'a' already. If I change the 'IF' snippet to "is 'True" as suggested, it does not work.

While this function does what I intended it to do, I feel it is not clean and I have no idea why "if n in a is 'True':" would not behave equal to the else part of the "if n in a is not 'True':" function.

Can somebody please help me understand this?

Upvotes: 1

Views: 110

Answers (4)

Whitesmell
Whitesmell

Reputation: 204

You can use

if n in a 

or

if n not in a

instead of the is 'True'.

Upvotes: 0

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29103

It is not a very pythonic way to use boolean check and then compare it with a string, so it would be better to do it this way:

a = [1,2,3]
b = [2,4,6]

def union(x,y):
    for v in y:
        if v not in x:
            x.append(v)
    return x

print union(a,b)

OR:

a.extend(set(b).difference(set(a)))
print a
>>> [1, 2, 3, 4, 6]

OR in case you don't care about new objects creating than:

print list(set(a).union(b))

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

in and is/is not are both relational operators, and in Python relational operators are chained. Therefore n in a is not 'True' is equivalent to n in a and a is not 'True', and n in a is 'True' is equivalent to n in a and a is 'True'. Clearly these are not negations of each other since they both have n in a.

But don't use is unless you know you need it, and never compare against a boolean either (unless yadda yadda).

Upvotes: 2

John La Rooy
John La Rooy

Reputation: 304205

You should just use True not the string 'True'

or better yet, just

if n not in a:
    a.append(n)

If you are a beginner, you may not realise that Python has a builtin type called set

set objects already have methods for intersection/union etc.

Upvotes: 1

Related Questions