1

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?

asked Mar 16, 2012 at 3:03

4 Answers 4

3

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))
answered Mar 16, 2012 at 3:07
Sign up to request clarification or add additional context in comments.

Comments

2

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).

answered Mar 16, 2012 at 3:09

Comments

1

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.

answered Mar 16, 2012 at 3:06

Comments

0

You can use

if n in a 

or

if n not in a

instead of the is 'True'.

Karlson
3,0881 gold badge27 silver badges53 bronze badges
answered Mar 16, 2012 at 3:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.