Python any() Built in Function

The any() function in Python returns True if any item in an iterable is true, otherwise it returns False. An iterable is an object that can be looped over, such as a list, a tuple, a set, a string or a dictionary. If the iterable is empty, the any() function also returns False. The any() function can be used to check if any element of an iterable satisfies a certain condition or if an iterable contains any true values.

Here are some examples of Python code using any():
 

# Check if any item in a list is negative
my_list = [1, 2, 3, -4]
print(any(x < 0 for x in my_list))
# prints True

# Check if any item in a tuple is odd
my_tuple = (2, 4, 6)
print(any(x % 2 != 0 for x in my_tuple))
# prints False

# Check if any item in a set is non-empty string
my_set = {"hello", "world", ""}
print(any(my_set))
# prints True

# Check if any character in a string is digit
my_string = "Python3"
print(any(my_string.isdigit()))
# prints True

# Check if any key in a dictionary starts with 'a'

my_dict = {"a": 1, "b": 2.0}
print(any(k.startswith('a') for k in my_dict.keys()))
# prints True

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions