user1647372
user1647372

Reputation:

Checking if elements exist in list using python

I am new to python and was wondering if someone could help me out with this. I am trying to see if the elements in b are in a. This is my attempt. Currently I am not getting any output. Any help would be appreciated, thank you!

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

for each in b:
    if each not in a == True:
        print(each + "is not in a")

Upvotes: 2

Views: 4410

Answers (8)

Keeto
Keeto

Reputation: 4208

I would like to add that if the two lists are large. This is not the best way to do it. Your algorithm is O(n^2). The best way is to traverse a, adding the elements as keys to a dictionary. Afterwards, traverse the second list, checking if the elements are already in the dictionary, this instead is an O(n) algorithm.

Upvotes: 0

AlexVhr
AlexVhr

Reputation: 2074

Another way:

for bb in b:
    try:
        a.index(bb)
    except:
        print 'value is not in the list: ' + str(bb)

Upvotes: 0

mgilson
mgilson

Reputation: 310227

You should be able to just say:

if each not in a:
   print ("%d is not in a" % each)

Your actual expression is using operator chaining:

if a > b > c:

parses as:

if (a > b) and (b > c):

in python. which means your expression is actually being parsed as:

if (each not in a) and (a == True):

but a == True will always return False, so that if block will never execute.

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1124748

You are testing two different things, and the outcome is False; Python is chaining the operators, effectively testing if (each is in a) and (a == True):

>>> 'a' in ['a'] == True
False
>>> ('a' in ['a']) and (['a'] == True)
False
>>> ('a' in ['a']) == True
True

You never need to test for True on an if statement anyway:

if each not in a:

is enough.

Upvotes: 4

Michael
Michael

Reputation: 2867

It is better to see the difference between B and A

 set(b).difference(set(a))

Upvotes: 1

Linus Thiel
Linus Thiel

Reputation: 39261

This is really easy using sets:

a = [1]
b = [1, 2]

only_in_b = set(b) - set(a)
# set([2])

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 114088

a = [1,2,3]
b = [1,2,3,4,5,6,7]
c = [7,8,9]

print set(a) <= set(b) #all elements of a are in b
print set(c) <= set(b) #all elements of c are in b

Upvotes: 1

alanmanderson
alanmanderson

Reputation: 8230

You don't need ==True. Just: if each not in a:

Upvotes: 0

Related Questions