Today, we’ll focus on the equivalent to JavaScript’s some and every.
The examples I provide handle both primitive values and objects.
Python Equivalent to JavaScript’s some()
Python’s equivalent of JavaScript’s some() is any().
|
|
Python Equivalent to JavaScript’s every()
Python’s equivalent of JavaScript’s every() is all().
|
|
Performance considerations
Both short-circuit, just like their JS counterparts:
any()stops at the first truthy result,all()stops at the first falsy one.
Use generator expressions (parentheses) not list comprehensions (brackets) to get the short-circuit benefit: all(x > 0 for x in data) lazily evaluates; all([x > 0 for x in data]) builds the entire list first, wasting memory and time.
A Few Caveats to Know
- With empty iterables, remember the following:
any([])returnsFalse,all([])returnsTrue. This matches JavaScript behavior but catches people off guard —all([])beingTrueis a vacuous truth. - No index access in Python, unlike JavaScript counterparts. If you need the index, use
enumerate()like we have seen for many previous articles on this series:any(val > 10 for i, val in enumerate(data)). - No built-in predicate parameter exists so you always need a generator expression.
- Truthiness differences between Python and JavaScript exist as the two programming languages use different falsy values.
0,"",None,[],{}are all falsy in Python. In JS,[]and{}are truthy. This matters if you’re doing bareany(items)without an explicit condition.
Follow me
Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.
Credit: Photo by Pixabay on Pexels.