TheAlgorithms/Python · error · Exception
List is empty
Error message
List is empty
What it means
LinkedDeque.first() raises a bare Exception('List is empty') when the deque has no elements, because it would otherwise dereference the sentinel's _next into the trailer. It is the accessor counterpart to last(); both are read-only peeks and do not modify the deque.
Source
Thrown at data_structures/linked_list/deque_doubly.py:72
successor._prev = predecessor
self._size -= 1
temp = node._data
node._prev = node._next = node._data = None
del node
return temp
class LinkedDeque(_DoublyLinkedBase):
def first(self):
"""return first element
>>> d = LinkedDeque()
>>> d.add_first('A').first()
'A'
>>> d.add_first('B').first()
'B'
"""
if self.is_empty():
raise Exception("List is empty")
return self._header._next._data
def last(self):
"""return last element
>>> d = LinkedDeque()
>>> d.add_last('A').last()
'A'
>>> d.add_last('B').last()
'B'
"""
if self.is_empty():
raise Exception("List is empty")
return self._trailer._prev._data
# DEque Insert Operations (At the front, At the end)
def add_first(self, element):
"""insertion in the frontView on GitHub (pinned to f5988cc097)
Solutions
- Guard the call with 'if not d.is_empty():' before peeking.
- Catch the exception with 'except Exception as e: if str(e) == "List is empty"' — note it is a generic Exception, not IndexError.
- Track the element count on the caller side so peek is only attempted when elements are known to exist.
Example fix
# before head = d.first() # Exception: List is empty # after head = d.first() if not d.is_empty() else None
Defensive patterns
Strategy: validation
Validate before calling
front = d.first() if not d.is_empty() else None
Try / catch
try:
front = d.first()
except Exception as e:
if 'List is empty' not in str(e):
raise
front = None Prevention
- Treat first() as conditional: always pair with is_empty().
- Note this library raises bare Exception, not IndexError, for empty peeks.
- In tests, assert the empty behavior explicitly since the doctests document it.
When it happens
Trigger: Calling first() on a freshly constructed LinkedDeque, or after remove_first()/remove_last() have drained all previously added elements.
Common situations: Producer/consumer code that peeks before checking is_empty(); porting code from collections.deque (where deque[0] raises IndexError, not Exception) and catching the wrong type; test setup that assumes the deque was pre-populated.
Related errors
- remove_first from empty list
- Invalid input needed_sum must be between 1 and 1000, power b
- Input value must be a 'int' type
- the value of both inputs must be positive
- both inputs must be positive integers
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/d691c833be2bb2b7.
Report an issue: GitHub.