Member-only story
8 Hidden Python Built-in Functions You Should Use in 2024
1. any()
Description: Returns True if at least one element of the iterable is True. If all elements are False, it returns False.
Use case: Useful for checking if at least one condition in a list of conditions is true.
nums = [0, 1, 2, 3]
print(any(num > 2 for num in nums))
True
2. all()
Description: Returns True if all elements in the iterable are True. If any element is False, it returns False.
Use case: Useful for checking if all conditions are satisfied.
nums = [2, 4, 6]
print(all(num % 2 == 0 for num in nums))
True
3. enumerate()
Description: Adds a counter to an iterable and returns it in a form of an enumerating object. The returned object is an iterator.
Use case: Helps in tracking the index and element when looping through a list or tuple.
items = ['apple', 'banana', 'cherry']
for index, item in enumerate(items):
print(index, item)