Wednesday 24 December 2014

Python built-in: any(), all()


any(iterable) -> bool


any(iterable)  is a built-in function in python's  __builtin__ module. It returns True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.
Now let's take a list.

>>>la = [True, False, False]
>>>any(ls)
>>>True

This returns True because at least one of the value in la was True. Let's take another list,

>>>lb = [False, False, False, False]
>>>any(lb)
>>>False 

So any() will return True if at least one of the value in the iterable is True else it will return False.

Example Usage:


>>>str = "Wikipedia is the seventh-most popular website \
...and constitutes the internet's largest and most popular \
...general reference work"
>>>keywords = ['Google', 'Wikipedia', 'Facebook', 'Microsoft']

We want to check if there is keyword from keywords list is present in the string str. With the use of any() function it can be done in a one-liner!

>>>any(keyword in str for keyword in keywords)
>>>True

That's awesome!! isn't it? But what sorcery is this? Breaking it down:

>>>[keyword in str for keyword in keywords]
>>>[False, True, False, False]

So it's like the earlier la, lb type list. It's returning True for the keyword 'Wikipedia'. Now what is happening in the list
compression is:

for keyword in keywords:
    if keyword in str:
        # append True in a_list
    return <a_list>

 

all(iterable) -> bool


This function takes an iterable as argument and returns True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True.

It will return if all the values in the iterable are True.

>>>all(la)
>>>False
>>>all(lb)
>>>False

>>>lc = [True]*3
>>>all(lc)
>>>True

 

Example Usage:


We are going to check if a list is a odd number list.

>>>all(map(lambda x:x%2==1, range(1, 10, 2)))
>>>True

Breaking it down:

>>> range(1, 10, 2)
>>>[1, 3, 5, 7, 9]

map() is a built-in which will return a list of result applying the lambda function to the item of the [1, 3, 5, 7, 9] list.

>>>map(lambda x:x%2==1, range(1, 10, 2))
>>>[True, True, True, True, True]
>>> all([True, True, True, True, True])
>>>True

Nice!!

No comments :

Post a Comment