first: Return the First True Value from an Iterable

2.0.2 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

Demonstrates the primary usage of the `first` function, including basic truthy checks, custom `key` functions, and specifying a `default` return value. It also includes an example of its common use with regular expressions.

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

view raw JSON →