3 Uses of the Ellipsis in Python



Python has a special built-in singleton object called “Ellipsis”. If we input three dots or the word “Ellipsis” in a Python interactive shell, the results are as following:

>>> ...
Ellipsis
>>> Ellipsis
Ellipsis

This simple object seems inconspicuous, but if we use it properly, it can make our lives easier.

This article will introduce the common three scenarios where the ellipsis can be used. After reading, you’ll like this cute singleton object of Python.


1. An Ellipsis Is a Placeholder for Unwritten Code

When designing a new module, we usually define some functions or classes but won’t implement them immediately. Because we only want to determine what we need to write in future and don’t care too much about the implementation details at this early stage. In this scenario, the ellipsis is our best friend:

def write_an_article():
    ...


class Article:
    ...

As shown above, we can just use an ellipsis as a placeholder for a function or a class.


Generally speaking, it’s a good programming practice that we design the needed things at first and implement them later. Because this way can help our mind keep clear about the whole structure and don’t get stuck in details right away.


By the way, the “pass” keyword can also be used as a placeholder in Python:

def write_an_article():
    pass


class Article:
    pass

We can decide which one to use based on personal preference. As far as I am concerned, the ellipsis is cuter.


2. Use an Ellipsis in Numpy To Omit Dimensions

The Numpy is an essential Python library for Data Science. When handling multi-dimension arrays in

Numpy, the ellipsis is helpful.


For example, if we have a 3-d matrix and want to slice it, there are three ways:

import numpy as np

A = np.random.rand(2, 3, 2