Search code examples
mongoenginelistfield

Mongoengine, how to get last element in listField


The familiar pythonic slicing conventions of myList[-1:][0] and myList[-1] are not available for Mongoengine listFields because it does not support negative indices. Is there an elegant way to get the last element of a list?

Error verbiage for posterity:

IndexError: Cursor instances do not support negative indices


Solution

  • You can access the last item with this code:

    myList[len(myList) - 1]