Hey Ninjas. It might be challenging to iterate and manually check each element in your code. Do you know how any in Python can help you? You can get a True or False value showing whether at least one element meets the condition. any in Python will be very useful for you and help you to improve your productivity.
This article will discuss how any Python functions and how to use them. So Ninjas, let's examine the any in Python more closely.
Understanding any in Python
any() in Python decides if at least one element in an iterable fulfils a particular condition. It will return you True if at least one element is True. It will return you False if all elements are False. It does not have to go through the whole iterable. It will stop checking as soon as it will finds the very first element that meets the condition you specified. You can use any() with a lambda function to check the iterable against some custom condition. any() make your code more readable. You can use any() in combo with other functions such as map() and filter(). You can work with logical expressions directly with any() help without a lambda function. You can use it in control statements such as if-else or while loops. Its inverse is all().
Syntax
any(iterable_item)
Parameters
iterable_item - It's the object you want to check for at least one True element. The iterable_object can be any sequence type, such as a list, tuple, set, or dictionary.
Return Type
It returns a boolean value. Depending on whether at least one element in the iterable given as the parameter satisfies a specific condition. It will return True if at least one sequence component is True. Otherwise, it will return False.
Complexity of any in Python
Now we will discuss time and space complexity of any() in Python.
Time Complexity
O(N) - N is the number of elements in iterable.
Reason - It checks each element and stops looking once it finds one. It will iterate over the entire iterable object if it does not find a True element. So in the worst case, the time taken will be O(N).
Space Complexity
O(1) - It has constant space complexity.
Reason - It's because it is not creating any new objects. It is only going through the existing iterable.
Now we will discuss some examples of passing different iterables to any in Python.
Passing Boolean Values
You can pass an array of boolean values to any() function. It will return True if at least one element in the given iterable item can be considered "truthy". Otherwise, it will return False.
CODE
# Firstly, we are defining a list with boolean values.
example_list = [False, False, True, True]
# Now check if at least one value in the sequence is True.
if any(example_list):
print("At least one value in our example is True")
# Create a new filtered list.
filtered_list = [i for indx, i in enumerate(example_list) if example_list[indx]]
# Finally printing the items.
print(filtered_list)
OUTPUT
EXPLANATION
Firstly we are defining a list of boolean values. Then we check if at least one value in the list is True using the any() function. If at least one True value is in the list, it prints an output message.
Then, we created a new filtered list by going through the original list and selecting only the True elements. Finally, we printed the filtered list.
Passing List of Integers
It involves using the any() function with a list understanding to convert each integer to a boolean value. We consider any nonzero value as True and 0 as False.
CODE
example_list = [0, 1, 2, 0, -1]
# Ensure to convert each element in example_list to a boolean value.
bool_list = [bool(i) for i in example_list]
# Now we are checking if any value in the bool_list is True.
if any(bool_list):
print("At least one value in example_list is nonzero")
else:
print("All values in example_list are zero")
OUTPUT
EXPLANATION
Firstly we create a list called example_list having integers. It then uses a list understanding to convert each element of example_list to a boolean value.
Passing a Set of Strings
If your set of strings has non-empty strings, the any() function will return True. Later, you can apply different conditions to the set elements using a previous list understanding.
CODE
# First defining a set of strings of your choice.
example_set = {"C++", "Java", "", "Python"}
# Now check if at least one string in the set is non-empty.
if any(example_set):
print("At least one string in example_set is non-empty")
else:
print("All strings in example_set are empty")
# Create a new set having only non-empty strings.
non_empty_set = {s for s in example_set if s}
# Printing the non-empty strings.
print(non_empty_set)
OUTPUT
EXPLANATION
We use any() function to check if at least one element in the example_set is truthy. The output from any() function will be True because we gave some non-empty strings. Later we create a new set called non_empty_set with only the non-empty strings from example_set.
Later we end up printing those non-empty strings.
Passing a Generator Expression
The any() function will check if any second element of a tuple is truthy (i.e., not an empty string). If the second element of the first and second tuples are non-empty strings, it will return True.
CODE
# Firstly, define a list of tuples of your choice.
example_list = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
# We are checking if any tuple in example_list has both elements greater than 4 (apply any condition of your choice).
result_achieved = any(x[0] > 4 and x[1] > 4 for x in example_list)
# Print the result.
if result_achieved:
print("At least one tuple in example_list has both elements greater than 4")
else:
print("No tuple in example_list has both elements greater than 4")
OUTPUT
EXPLANATION
Firstly, we defined a list of tuples called example_list with five tuples, each having two elements. Then, we use the any() function to check if any tuple in example_list has elements more significant than 4. We use a generator expression that checks if each tuple's first and second elements are greater than 4. Finally, we assign the resulting boolean value to the variable result_achieved.
all() VS any() in Python
You can use both functions according to your need with any iterable item, including lists, tuples, sets, and more. Here are some more points related to all() and any() functions in Python:
all()
any()
Purpose
It will return True only when all elements in an iterable are true.
It will return True only when a minimum of one element in an iterable is true.
Return Type
True or False
True or False
Stopping Iteration
It will stop when it finds the first False element in the iterable.
It will stop when it finds the first True element in the iterable.
Syntax
all(iterable_item)
any(iterable_item)
Time Complexity
O(N)
O(N)
Space Complexity
O(1)
O(1)
Now we will discuss some pros and cons of any in Python:
Pros of any in Python
Here are some pros of using any() in Python:
It has a short syntax.
It takes little effort to learn and use.
It will quickly decide if any element in an iterable is true.
It can improve code efficiency by not going through the entire sequence.
You can combine it with other Python functions for powerful functionality.
It will save you time in writing complex code.
Cons of any in Python
Here are some cons of using any() in Python:
It can only check for a single condition at a time.
You cannot change or modify the original iterable tem you passed.
It returns boolean values only, not actual elements that fulfil the condition.
It cannot decide the index or number of the elements satisfying the condition.
What will any() return if you are passing empty iterable items?
any() will return False if the iterable object given to it is empty. It's because there are no elements in the iterable to iterate over and check.
Can you use any() with multiple conditions?
Yes, you can use any() with multiple conditions by connecting them using logical OR operators. You can also use parentheses to create conditions for more complex rational expressions.
Will you use any() with lambda functions?
Yes, you can use any() with lambda functions when you want to create more complex conditions. Lambda functions can be handy when you need a fast, one-line function for a single operation.
Does any() modify the original iterable item during the whole process?
No, any() will not modify the original iterable item. It will return True if at least one element in an iterable is True. And False otherwise. It will not change the original iterable object in any case at all.
Will any() work with non-boolean values?
Yes, it can work with non-boolean values. In fact, it will work with iterables that contain any value, not just boolean values.
Conclusion
We thoroughly covered any in Python in this article. The article explains the any in Python definition, it's functioning, its pros and cons and how you can use it in various cases. We have discussed several code examples to make learning more manageable for you. You can read the articles attached below to learn and practice more. These articles will help you improve your concepts related to any in Python.