Skip to content

Conversation

@pierrelegall
Copy link
Contributor

Summary

See discussion about it.

Add List.first!/1 and List.last!/1 functions that raise an ArgumentError when the list is empty.

  • List.first!/1 - returns the first element or raises if empty
  • List.last!/1 - returns the last element or raises if empty

Motivation

The existing List.first/2 and List.last/2 functions return a default value when the list is empty. The new bang variants provide an alternative when an empty list indicates a bug, following the pattern established by List.keyfind!/3, Map.fetch!/2, and Enum.fetch!/2.

Examples

iex> List.first!([1, 2, 3])
1

iex> List.first!([])
** (ArgumentError) trying to get the first element of an empty list

iex> List.last!([1, 2, 3])
3

iex> List.last!([])
** (ArgumentError) trying to get the last element of an empty list

Test plan

  • Added unit tests for first!/1 and last!/1
  • Added doctests with examples
  • All existing List tests pass


"""
@spec first!([elem, ...]) :: elem when elem: var
def first!(list)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit:

Suggested change
def first!(list)
def first!(list)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already merged.

Is there a convention? Is there is, should we add this as a formatting rule?

@josevalim josevalim merged commit 7b22b8e into elixir-lang:main Jan 29, 2026
@josevalim
Copy link
Member

💚 💙 💜 💛 ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

4 participants