Multiple Items Existence Check in Python

This is new for me, sometimes I want to do this:

aList = [1, 2, 3, 5, 7];

if (2, 3) in aList:   # I want to check whether 2 and 3 is in aList
    doSomethingCool( );

that code right there is a logical error, I thought the interpreter will search aList for items inside the tuple while the truth is that it will look for the existence of a tuple with 2 and 3 in it inside aList.

Thanks to some guy’s code which I happened to stumble upon, now I know that I can use all( ) function to do that. A leaner solution than the tedious enumeration of all items and checking it one by one. Here’s a demonstration:

# instead of this ..
allFound = True;
for num in (2, 3):
    if not (num in aList):
        allFound = False;
if allFound:
    doSomethingCool( );

# now I can use this ...
if all(num in aList for num in (2, 3)):
    doSomethingCool( );

wow, look at that! It makes perfect sense because most of the gist in that sample is a list comprehension and all( ) made up the invisible AND between the list items. Another similar function to all( ) is the appropriately-named any( ) which having the effect of OR instead of AND.


Leave a comment

Filed under Ilmu

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s