24

I have two lists:

mylist = ['total','age','gender','region','sex']
checklist = ['total','civic']

I have to work with some code I have inherited which looks like this:

for item in mylist:
    if item in checklist:
        do something:

How can I work with the code above to tell me that 'civic' is not in mylist?.

This would've been the ideal way to do it but I cant use it, don't ask me why.

for item in checklist:
    if item not in mylist:
        print item

Outcome:

civic
Paco
  • 4,520
  • 3
  • 29
  • 53
Boosted_d16
  • 13,340
  • 35
  • 98
  • 158
  • 1
    it works for me with Python 2.7. "if item not in mylist" or "if not item in mylist" both works – Jerry T Oct 20 '15 at 21:12

4 Answers4

55

Your code should work, but you can also try:

    if not item in mylist :
Will
  • 891
  • 1
  • 7
  • 11
  • This makes the most logical sense to me and works! Thanks Will - not sure why this is on the bottom. Lets push it up! – embulldogs99 Jun 28 '20 at 02:36
13

How about this?

for item in mylist:
    if item in checklist:
        pass
    else:
       # do something
       print item
Santosh Ghimire
  • 3,087
  • 8
  • 35
  • 63
3

if I got it right, you can try

for item in [x for x in checklist if x not in mylist]:
    print (item)
Yury Wallet
  • 1,474
  • 1
  • 13
  • 24
1

You better do this syntax

if not (item in mylist):  
    Code inside the if
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
  • 7
    actually, PEP8 prefers "item not in mylist" over "not item in mylist". https://www.python.org/dev/peps/pep-0008/#programming-recommendations (analogous to "is not" vs "not ... is") – Quantum7 Sep 06 '17 at 15:57