Short-Circuit Evaluation for Safe Lookup

Medium ⏱ 12 min 58% acceptance ★★★★★ 4.7
Write a function first_item_or(items, default) that returns the first element of list items if the list is non-empty, otherwise returns default. Implement it as a single expression using and/or short-circuit evaluation (not an if/else statement), relying on the fact that Python's and/or return operand values, not just booleans.

Examples

Example 1
Input
first_item_or([5, 6, 7], 0)
Output
5
Explanation

List is non-empty, so its first element is returned.

Example 2
Input
first_item_or([], 0)
Output
0
Explanation

Empty list is falsy, so default is returned.

Constraints

  • items is a list; default is any value.
  • Elements of items, if present, are always truthy (so this pattern is safe here).

Topics

Operatorsshort-circuit evaluation

Companies

MicrosoftNetflix

Hints

Hint 1

`items and items[0]` evaluates to items[0] only when items is non-empty (truthy).

Hint 2

Chain with `or default` to fall back when the list is empty.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.