How does Python use Any and All? Code samples and analysis

Any and All are two built-in plugins provided in python for continuous And/Or.

 

Any

Returns true if any of the items are True. Returns False if empty or all false. Think of anything as a series of OR operations on the provided iterables.

It will short-circuit execution, i.e. stop execution as soon as the result is known.

Syntax: any (iteration list)

# Since all are false, false is returned
print ( any ([ False , False , False , False ]))
  
# Here the method will short-circuit at the
# second item (True) and will return True.
print ( any ([ False , True , False , False ]))
  
# Here the method will short-circuit at the
# first (True) and will return True.
print ( any ([ True , False , False , False ]))

output:

False
True
True

 

All

Returns true if all items are True (or the iterable is empty). Think of everything as a series of AND operations on the provided iterable. This also short-circuits execution, i.e. stops execution as soon as the result is known.

Syntax: all (iteration list)

# Here all the iterables are True so all
# will return True and the same will be printed
print ( all ([ True , True , True , True ]))
  
# Here the method will short-circuit at the 
# first item (False) and will return False.
print ( all ([ False , True , True , False ]))
  
# This statement will return False, as no
# True is found in the iterables
print ( all ([ False , False , False ]))

output:

True
False
False

Practical examples

# This code explains how can we 
# use 'any' function on list 
list1 = []
list2 = []
  
# Index ranges from 1 to 10 to multiply
for i in range ( 1 , 11 ):
     list1.append( 4 * i) 
  
# Index to access the list2 is from 0 to 9
for i in range ( 0 , 10 ):
     list2.append(list1[i] % 5 = = 0 )
  
print ( 'See whether at least one number is divisible by 5 in list 1=>' )
print ( any (list2))

The output is as follows:

See whether at least one number is divisible by 5 in list 1=>
True

 

# Illustration of 'all' function in python 3
  
# Take two lists 
list1 = []
list2 = []
  
# All numbers in list1 are in form: 4*i-3
for i  in range ( 1 , 21 ):
     list1.append( 4 * i - 3 )
  
# list2 stores info of odd numbers in list1
for i in range ( 0 , 20 ):
     list2.append(list1[i] % 2 = = 1 )
  
print ( 'See whether all numbers in list1 are odd =>' )
print ( all (list2))

The output is as follows:

See whether all numbers in list1 are odd =>
True

Truth Table:-

Please write a comment if you find anything incorrect or would like to share more information on the above topics.

First of all, your interview preparation enhances your data structure concepts through: Python DS course.

For more information about Python development technology, please refer to: lsbin - IT development technology : https://www.lsbin.com/

Check out more Python-related content below:

Guess you like

Origin blog.csdn.net/u014240783/article/details/115387002