Python any built in function

Python any() Function

The any() function returns True if any item in an iterable are true, otherwise it returns False.

If the iterable object is empty, the any() function will return False.

Syntax

Parameter Values

More Examples

Example

Check if any item in a tuple is True:

Example

Check if any item in a set is True:

Example

Check if any item in a dictionary is True:

Note: When used on a dictionary, the any() function checks if any of the keys are true, not the values.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Python any()

The any() function returns True if any element of an iterable is True . If not, it returns False .

Example

boolean_list = ['True', 'False', 'True'] 
# check if any element is true result = any(boolean_list)
print(result) # Output: True

any() Syntax

any() Parameters

The any() function takes an iterable (list, string, dictionary etc.) in Python.

any() Return Value

The any() function returns a boolean value:

  • True if at least one element of an iterable is true
  • False if all elements are false or if an iterable is empty
Condition Return Value
All values are true True
All values are false False
One value is true (others are false) True
One value is false (others are true) True
Empty Iterable False

Example 1: Using any() on Python Lists

# True since 1,3 and 4 (at least one) is true l = [1, 3, 4, 0] 
print(any(l))
# False since both are False l = [0, False]
print(any(l))
# True since 5 is true l = [0, False, 5]
print(any(l))
# False since iterable is empty l = []
print(any(l))

The any() method works in a similar way for tuples and sets like lists.

Example 2: Using any() on Python Strings

# At east one (in fact all) elements are True s = "This is good" 
print(any(s))
# 0 is False # '0' is True since its a string character s = '000' print(any(s)) # False since empty iterable s = ''
print(any(s))

Example 3: Using any() with Python Dictionaries

In the case of dictionaries, if all keys (not values) are false or the dictionary is empty, any() returns False . If at least one key is true, any() returns True .

# 0 is False d = print(any(d)) # 1 is True d = 
print(any(d))
# 0 and False are false d = print(any(d)) # iterable is empty d = <>
print(any(d))
# 0 is False # '0' is True d = print(any(d))
False True False False True

Источник

How To Use the all, any, max, and min Functions in Python

Python includes a number of built-in functions—these are global Python functions that can be called from any Python code without importing additional modules. For example, you can always call the print built-in function to output text.

Several of the built-in functions ( all , any , max , and min among them) take iterables of values as their argument and return a single value. An iterable is a Python object that can be “iterated over”, that is, it will return items in a sequence such that you can use it in a for loop. Built-in functions are useful when, for example, you want to determine if all or any of the elements in a list meet a certain criteria, or find the largest or smallest element in a list.

In this tutorial, you will use the built-in functions all , any , max , and min .

Prerequisites

To get the most out of this tutorial, it is recommended to have:

  • Some familiarity with programming in Python 3. You can review our How To Code in Python 3 tutorial series for background knowledge.
  • The Python Interactive Console, if you would like to try out the example code in this tutorial you can use the How To Work with the Python Interactive Console tutorial.

Using all

The built-in function all checks if every element in an iterable is True . For example:

If you run the previous code, you will receive this output:

In this first example, you call all and give it a list with two elements (two True Boolean values). Since every element in the iterable is True , the output was True .

all will return False if one or more elements in the given iterable is False :

If you run the previous code, you’ll receive this output:

You call all with a list containing three elements including one False Boolean value. Since one of the elements in the iterable was False , the output of the call to all was False .

Notably, all stops iterating and immediately returns False as soon as it encounters the first False entry in an iterable. So, all can be useful if you want to check successive conditions that may build on each other, but return immediately as soon as one condition is False .

A special case to be aware of is when all is given an empty iterable:

If you run the previous code, you’ll receive this output:

When you give all an empty iterable (for example, an empty list like all([]) ), its return value is True . So, all returns True if every element in the iterable is True or there are 0 elements.

all is particularly helpful when combined with generators and custom conditions. Using all is often shorter and more concise than if you were to write a full-fledged for loop. Let’s consider an example to find out whether there are elements in a list that start with «s» :

animals = ["shark", "seal", "sea urchin"] all(a.startswith("s") for a in animals) 

If you run the previous code, you will receive this output:

You call all with a generator as its argument. The generator produces a Boolean for each element in the animals list based on whether or not the animal starts with the letter s . The final return value is True because every element in the animals list starts with s .

Consider that the equivalent code written using a full-fledged for loop would have been significantly more verbose:

animals = ["shark", "seal", "sea urchin"] def all_animals_start_with_s(animals): for a in animals: if not a.startswith("s"): return False return True print(all_animals_start_with_s(animals)) 

Without all , your code for determining if all the animals start with the letter s requires several more lines to implement.

Next, you’ll look at the sibling function to all : any .

Using any

You can use the built-in function any to check if any element in an iterable is True . For example:

If you run the previous code, you’ll receive this output:

You call any and give it a list with two elements (a False Boolean value and a True Boolean value). Since one or more element in the iterable was True , the output was also True .

any will return False if, and only if, 0 of the elements in the given iterable are True :

If you run the previous code, you’ll receive this output:

You call any with a list containing three elements (all False Boolean values). Since 0 of the elements in the iterable is True , the output of the call to any is False .

Notably, any stops iterating and immediately returns True as soon as it encounters the first True entry in an iterable. So, any can be useful if you want to check successive conditions, but return immediately as soon as one condition is True .

any —like its sibling method all —is particularly helpful when combined with generators and custom conditions (in place of a full for loop). Let’s consider an example to find out whether there are elements in a list that end with «urchin» :

animals = ["shark", "seal", "sea urchin"] any(s.endswith("urchin") for s in animals) 

You will receive this output:

You call any with a generator as its argument. The generator produces a Boolean for each element in the animals list based on whether or not the animal ends with urchin . The final return value is True because one element in the animals list ends with urchin .

Note: When any is given an empty iterable (for example, an empty list like any([]) ), its return value is False . So, any returns False if there are 0 elements in the iterable or all the elements in the iterable are also False .

Next, you’ll review another built-in function: max .

Using max

The built-in function max returns the largest element given in its arguments. For example:

max is given a list with four integers as its argument. The return value of max is the largest element in that list: 8 .

The output will be the following:

If given two or more positional arguments (as opposed to a single positional argument with an iterable), max returns the largest of the given arguments:

If you run the previous code, you will receive this output:

max is given three individual arguments, the largest of which being 3 . So, the return value of the call to max is 3 .

Just like any and all , max is particularly helpful because it requires fewer lines to use than equivalent code written as a full for loop.

max can also deal with objects more complex than numbers. For example, you can use max with dictionaries or other custom objects in your program. max can accommodate these objects by using its keyword argument named key .

You can use the key keyword argument to define a custom function that determines the value used in the comparisons to determine the maximum value. For example:

entries = ["id": 9>, "id": 17>, "id": 4>] max(entries, key=lambda x: x["id"]) 

The output will be the following:

You call max with a list of dictionaries as its input. You give an anonymous lambda function as the key keyword argument. max calls the lambda function for every element in the entries list and returns the value of the «id» key of the given element. The final return value is the second element in entries : . The second element in entries had the largest «id» value, and so was deemed to be the maximum element.

Note that when max is called with an empty iterable, it refuses to operate and instead raises a ValueError :

If you run this code, you will receive the following output:

Output
Traceback (most recent call last): File "max.py", line 1, in max([]) ValueError: max() arg is an empty sequence

You call max with an empty list as its argument. max does not accept this as a valid input, and raises a ValueError Exception instead.

max has a counterpart called min , which you’ll review next.

Using min

The built-in function min returns the smallest element given in its arguments. For example:

You give min a list with four integers as its argument. The return value of min is the smallest element in that list: 0 .

If given two or more positional arguments (as opposed to a single positional argument with an iterable), min returns the smallest of the given arguments:

If you run the previous code, you will receive this output:

You give min three individual arguments, the smallest of which being -1 . So, the return value of the call to min is -1 .

Like max , min supports the keyword argument named key so that you can pass objects more complex than numbers into it. Using the key argument allows you to use the min function with any custom objects your program might define.

You can use the key keyword argument to define a custom function that determines the value used in the comparisons to determine the minimum value. For example:

entries = ["id": 9>, "id": 17>, "id": 4>] min(entries, key=lambda x: x["id"]) 

You call min with a list of dictionaries as its input. You give an anonymous lambda function as the key keyword argument. min calls the lambda function for every element in the entries list and returns the value of the «id» key of the given element. The final return value is the third element in entries : . The third element in entries had the smalled «id» value, and so was deemed to be the minimum element.

Like max , when you call min with an empty iterable, it refuses to operate and instead raises a ValueError :

If you run the previous code, you will receive this output:

Output
Traceback (most recent call last): File "min.py", line 1, in min([]) ValueError: min() arg is an empty sequence

You call min with an empty list as its argument. min does not accept this as a valid input, and raises a ValueError Exception instead.

Conclusion

In this tutorial, you used the Python built-in functions all , any , max , and min . You can learn more about the functions all , any , max , and min and other Python built-in in the Python docs.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Читайте также:  Vs code html комментарии
Оцените статью