python - if not in list [duplicate]
Asked Answered
B

4

25

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
Basinet answered 3/4, 2014 at 9:50 Comment(1)
it works for me with Python 2.7. "if item not in mylist" or "if not item in mylist" both worksPlacable
M
13

How about this?

for item in mylist:
    if item in checklist:
        pass
    else:
       # do something
       print item
Mim answered 3/4, 2014 at 9:53 Comment(2)
it works for me with Python 2.7. "if item not in mylist" or "if not item in mylist" both worksPlacable
Actually the the preferred syntax is a not in bGeophysics
R
55

Your code should work, but you can also try:

    if not item in mylist :
Ricercare answered 8/12, 2014 at 21:50 Comment(1)
This makes the most logical sense to me and works! Thanks Will - not sure why this is on the bottom. Lets push it up!Somnambulation
M
13

How about this?

for item in mylist:
    if item in checklist:
        pass
    else:
       # do something
       print item
Mim answered 3/4, 2014 at 9:53 Comment(2)
it works for me with Python 2.7. "if item not in mylist" or "if not item in mylist" both worksPlacable
Actually the the preferred syntax is a not in bGeophysics
C
5

if I got it right, you can try

for item in [x for x in checklist if x not in mylist]:
    print (item)
Cooperate answered 8/6, 2018 at 21:50 Comment(0)
U
1

You better do this syntax

if not (item in mylist):  
    Code inside the if
Unfriendly answered 13/10, 2016 at 17:44 Comment(1)
actually, PEP8 prefers "item not in mylist" over "not item in mylist". python.org/dev/peps/pep-0008/#programming-recommendations (analogous to "is not" vs "not ... is")Earl

© 2022 - 2024 — McMap. All rights reserved.