first: Return the First True Value from an Iterable
first is an MIT-licensed Python package with a single, simple function that efficiently returns the first 'truthy' value from an iterable, or `None` if no such value exists. It offers optional `key` function customization for complex truthiness evaluation and a `default` parameter for specifying a fallback value. Currently at version 2.0.2, the library maintains a stable, infrequent release cadence focused on core functionality and compatibility.
Warnings
- breaking Version 2.0.0 dropped explicit support for Python 3.3. The library now officially supports Python 2.7 and Python 3.4+.
- breaking Version 2.0.0 removed `six` as a dependency. While unlikely to directly break user code, it reflects an internal refactoring for Python 2/3 compatibility.
- gotcha The `first` function's definition of 'true value' (often called 'truthy') is consistent with Python's `any()` and `all()` functions. This means values like `True`, `1`, `'foo'`, or `[None]` are considered truthy, while `None`, `False`, `[]`, `''`, or `0` are falsy. Be mindful of this behavior, especially when dealing with empty collections or zero values.
- deprecated Although `first` version 2.x wheels (`first-2.0.2-py2.py3-none-any.whl`) indicate Python 2 compatibility, Python 2 reached its End-of-Life (EOL) in January 2020. Running new or updated projects on Python 2 is highly discouraged due to lack of security updates and community support.
Install
-
pip install first
Imports
- first
from first import first
Quickstart
from first import first
# Basic usage: returns the first truthy item
value1 = first([0, None, False, [], (), 42])
print(f"First truthy value: {value1}") # Expected: 42
# Using a key function: returns the first even number
value2 = first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
print(f"First even number: {value2}") # Expected: 4
# Using a default value if no truthy item is found
value3 = first([0, None, False, [], ()], default='no match')
print(f"With default: {value3}") # Expected: no match
# Useful with regular expressions
import re
re1 = re.compile('b(.*)')
re2 = re.compile('a(.*)')
m = first(regexp.match('abc') for regexp in [re1, re2])
if m:
print(f"Regex match group 1: {m.group(1)}") # Expected: bc