Skip to content

Commit

Permalink
Allow first to supply a default value returned when iterable is empty.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Mar 25, 2018
1 parent f527c3d commit e773284
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
5 changes: 5 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
2.2
===

* ``first`` now accepts a default value, same as ``next``.

2.1.1
=====

Expand Down
15 changes: 13 additions & 2 deletions jaraco/itertools.py
Original file line number Diff line number Diff line change
Expand Up @@ -712,7 +712,7 @@ def takewhile_peek(predicate, iterable):
yield next(iterable)


def first(iterable):
def first(iterable, *args):
"""
Return the first item from the iterable.
Expand All @@ -724,9 +724,20 @@ def first(iterable):
>>> first(iter)
0
Raises StopIteration if no value is present.
>>> first([])
Traceback (most recent call last):
...
StopIteration
Pass a default to be used when iterable is empty.
>>> first([], None)
"""
iterable = iter(iterable)
return next(iterable)
return next(iterable, *args)


def last(iterable):
Expand Down

0 comments on commit e773284

Please sign in to comment.