Python all() Built in Function
The all() function in Python returns True if all items in an iterable are 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 all() function also returns True. The all() function can be used to check if all elements of an iterable satisfy a certain condition or if an iterable contains any false values.
Here are some examples of Python code using all():
# Check if all items in a list are positive
my_list = [1, 2, 3, 4]
print(all(x > 0 for x in my_list)) # prints True
# Check if all items in a tuple are even
my_tuple = (2, 4, 6)
print(all(x % 2 == 0 for x in my_tuple)) # prints True
# Check if all items in a set are non-empty strings
my_set = {"hello", "world", ""}
print(all(my_set)) # prints False
# Check if all characters in a string are alphabets
my_string = "Python"
print(all(my_string.isalpha())) # prints True
# Check if all values in a dictionary are integers
my_dict = {"a": 1, "b": 2.0}
print(all(isinstance(v, int) for v in my_dict.values())) # prints False
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment