any() and all() functions in Python - Time & Space Complexity
We want to understand how the time taken by any() and all() changes as the input list grows.
How does checking conditions on many items affect the work done?
Analyze the time complexity of the following code snippet.
def check_any(nums):
return any(x > 0 for x in nums)
def check_all(nums):
return all(x > 0 for x in nums)
This code checks if any number is positive and if all numbers are positive in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each item in the list one by one.
- How many times: Up to all items, but may stop early if condition met.
As the list gets bigger, the number of checks can grow up to the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The work grows roughly in a straight line with input size, but can stop early if condition is met.
Time Complexity: O(n)
This means the time to check grows linearly with the number of items in the list.
[X] Wrong: "any() and all() always check every item no matter what."
[OK] Correct: Actually, they stop checking as soon as the answer is clear, so they often do less work than the list size.
Understanding how any() and all() work helps you explain efficient checks over lists, a common task in coding problems.
"What if we changed the input from a list to a generator? How would the time complexity change?"