What does the Ellipsis object do? What does the Ellipsis object do? python python

What does the Ellipsis object do?


This came up in another question recently. I'll elaborate on my answer from there:

Ellipsis is an object that can appear in slice notation. For example:

myList[1:2, ..., 0]

Its interpretation is purely up to whatever implements the __getitem__ function and sees Ellipsis objects there, but its main (and intended) use is in the numpy third-party library, which adds a multidimensional array type. Since there are more than one dimensions, slicing becomes more complex than just a start and stop index; it is useful to be able to slice in multiple dimensions as well. E.g., given a 4x4 array, the top left area would be defined by the slice [:2,:2]:

>>> aarray([[ 1,  2,  3,  4],       [ 5,  6,  7,  8],       [ 9, 10, 11, 12],       [13, 14, 15, 16]])>>> a[:2,:2]  # top leftarray([[1, 2],       [5, 6]])

Extending this further, Ellipsis is used here to indicate a placeholder for the rest of the array dimensions not specified. Think of it as indicating the full slice [:] for all the dimensions in the gap it is placed, so for a 3d array, a[...,0] is the same as a[:,:,0] and for 4d, a[:,:,:,0], similarly, a[0,...,0] is a[0,:,:,0] (with however many colons in the middle make up the full number of dimensions in the array).

Interestingly, in python3, the Ellipsis literal (...) is usable outside the slice syntax, so you can actually write:

>>> ...Ellipsis

Other than the various numeric types, no, I don't think it's used. As far as I'm aware, it was added purely for numpy use and has no core support other than providing the object and corresponding syntax. The object being there didn't require this, but the literal "..." support for slices did.


In Python 3, you can¹ use the Ellipsis literal ... as a “nop” placeholder for code that hasn't been written yet:

def will_do_something():    ...

This is not magic; any expression can be used instead of ..., e.g.:

def will_do_something():    1

(Can't use the word “sanctioned”, but I can say that this use was not outrightly rejected by Guido.)

¹ 'can' not in {'must', 'should'}


As of Python 3.5 and PEP484, the literal ellipsis is used to denote certain types to a static type checker when using the typing module.

Example 1:

Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis, for example Tuple[int, ...]

Example 2:

It is possible to declare the return type of a callable without specifying the call signature by substituting a literal ellipsis (three dots) for the list of arguments:

def partial(func: Callable[..., str], *args) -> Callable[..., str]:    # Body


matomo