any and all

Testing conditions on iterables

Interview Relevant: Boolean operations

any and all

Check conditions across iterables.

Code Examples

Using any and all for conditions.

python
1nums = [1, 2, 3, 4, 5]
2
3# any - True if any element is truthy
4any([False, True, False])  # True
5any([0, 0, 0])             # False
6any(x > 3 for x in nums)   # True
7
8# all - True if all elements are truthy
9all([True, True, True])    # True
10all([1, 2, 0])             # False
11all(x > 0 for x in nums)   # True
12
13# Empty iterables
14any([])  # False
15all([])  # True (vacuous truth)
16
17# Practical examples
18# Check if any string is empty
19strings = ["hello", "world", ""]
20any(s == "" for s in strings)  # True
21
22# Check if all positive
23all(x > 0 for x in nums)  # True

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In