Python all usage details and examples

Python all Usage Detailed Explanation and Examples

The Python all function is a built-in function that takes an iterable object as an argument and returns a Boolean value. The all function returns True if all elements in the iterable are true (i.e., non-zero, non-empty, non-None, etc.); otherwise, it returns False.

Below are three examples illustrating the use of the all function:

  1. Determine whether all elements in a list are True:
nums = [1, 2, 3, 4, 5]
result = all(nums)
print(result) # Outputs True

In this example, all elements in the list nums are nonzero (True), so the all function returns True.

  1. Determine if all values in a dictionary are true:
person = {"name": "Alice", "age": 25, "gender": "female"}
result = all(person.values())
print(result) # Outputs True

In this example, all values in the dictionary person are non-empty, so the all function returns True.

  1. Determine whether all characters in a string are alphabetic:
word = "HelloWorld"
result = all(c.isalpha() for c in word)
print(result) # Outputs True

In this example, all characters in the string word are alphabetic, so the all function returns True. A generator expression is used here to determine whether each character in the string is alphabetic.

In summary, the all function can be used to determine whether all elements in an iterable object meet a condition. If all elements meet the condition, it returns True; otherwise, it returns False.

Leave a Reply

Your email address will not be published. Required fields are marked *