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 front

View on GitHub (pinned to f5988cc097)

Solutions

  1. Guard the call with 'if not d.is_empty():' before peeking.
  2. Catch the exception with 'except Exception as e: if str(e) == "List is empty"' — note it is a generic Exception, not IndexError.
  3. 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

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


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/d691c833be2bb2b7. Report an issue: GitHub.