The Ellipsis Object in Python

There is a special object in Python called Ellipsis, which can be used as a syntactic element in various contexts.
The type of the Ellipsis object is ‘ellipsis’, and there is only one.

The syntactic representation of the Ellipsis object is (three periods).

A natural example usage is as a list element:

myList = [1, 2, ..., 10]

Note that when printing this list, the Ellipsis object is printed explicitly:

[1, 2, Ellipsis, 10]

Further, the Ellipsis can be assigned to variables:

x = ...

We can test its type:

type(...)

Output:

<class 'ellipsis'>

We can test for equality with Ellipsis:

... == x

Output:

True

Largely, the purpose of the object is to provide a mechanism for libraries and frameworks to add special features with a nice syntax.
It does not define any logic for generating values.

For example, suppose we are writing a mathematical library.
We can imagine a function to determine if a given list is infinite.
The Ellipsis can provide a nice clean looking syntax to represent this, consistent with mathematical notation. The following example shows this.

We test the last element of the list for the Ellipsis to determine if the input represents an infinite list. Note that this is syntactic manipulation and we would have to add explicit logic to build this idea out further.

def is_infinite(inputList):
  return inputList[-1] == ...

# Test cases.
listA = [1, 2, 3, ...]
listB = [1, 2, 3, 4, 5]

print(is_infinite(listA))
print(is_infinite(listB))

Output:

True
False

One notable known usage of the Ellipsis is in numpy, where it can be used to refer to all remaining dimensions of an array.

 

Leave a Reply

Your email address will not be published. Required fields are marked *