any() and all()
The Python built-in functions any()
and all()
are often used to check for the presence or absence of specific conditions in a collection, such as a list or dictionary. Below are examples using any()
and all()
with lists of string values, as well as their respective outputs.
Examples using any()
Check if any string in the list is "apple"
fruits = ["banana", "cherry", "apple", "date"] has_apple = any(fruit == "apple" for fruit in fruits) print(has_apple) # Output: True
Check if any string in the list starts with the letter "a"
fruits = ["banana", "cherry", "apple", "date"] starts_with_a = any(fruit.startswith("a") for fruit in fruits) print(starts_with_a) # Output: True
Check if any string in the list has length greater than 5
fruits = ["banana", "cherry", "apple", "date"] has_long_name = any(len(fruit) > 5 for fruit in fruits) print(has_long_name) # Output: True
Examples using all()
Check if all strings in the list are in lowercase
words = ["hello", "world", "python"] all_lowercase = all(word.islower() for word in words) print(all_lowercase) # Output: True
Check if all strings in the list end with the letter "e"
words = ["apple", "orange", "grape"] all_end_with_e = all(word.endswith("e") for word in words) print(all_end_with_e) # Output: True
Check if all strings in the list have length less than 10
fruits = ["banana", "cherry", "apple", "date"] all_short_names = all(len(fruit) < 10 for fruit in fruits) print(all_short_names) # Output: True
These examples illustrate how any()
and all()
can be used to efficiently check for specific conditions in a list of string values.