Skip to content

Python three dots

  • by

Python three dots (Ellipsis) means the object seems inconspicuous. It is a singleton Object i.e., provides easy access to single instances.

Python three dots or Ellipsis

Simple example code use of Three dots(…) or Ellipsis in Python 3.

Use an Ellipsis in Numpy

Accessing and slicing multidimensional Arrays/NumPy indexing. Select all first-row elements from the 4-dimensional matrix of order 2x2x2x2 (in case of row-major structure) in the 4th dimension using the ellipsis notation.

import numpy as np

array = np.random.rand(2, 2, 2, 2)
print(array[..., 0])
print(array[Ellipsis, 0])

Output:

Python three dots or Ellipsis

In type hinting

Ellipsis is used in specifying type hints using the typing module (e.g. Callable[…, str]).

from typing import Callable

def inject(get_next_item: Callable[..., str]) -> None:
			...
# Argument type is assumed as type: Any
def foo(x: ...) -> None:
			...

Pass Statement inside Functions

# style1
def foo():
    pass
# style2
def foo():
    ...
# both the styles are same

Ellipsis can also be used as a default argument value. Especially when you want to distinguish between not passing in value and passing in None.

def foo(x = ...):
    return x
 
print(foo)

Error

Use colons for accessing the other dimensions i.e. ‘ : ‘.

l[...,1,...]

Source: https://www.geeksforgeeks.org/

Here are a few common use cases:

Slice Notation: You can use the ellipsis as a placeholder in slice notation.

my_list = [1, 2, 3, 4, 5]
partial_list = my_list[1:3, ..., 4:6]

In this example, ... is a shorthand for saying “everything in between.”

Numpy Arrays: In the NumPy library, the ellipsis is often used in multidimensional arrays to represent multiple colons.

import numpy as np

arr = np.random.random((3, 4, 5))
result = arr[..., 2]

Here, ... is a concise way of saying “all the other dimensions.”

Type Hints: The ellipsis can be used in type hints to represent “to be implemented” or “type not yet specified.”

def my_function() -> ...:
    # Implementation yet to be defined
    pass

This is commonly used in stub files where the implementation details are not provided.

Debugger: In debugging tools like pdb, the ellipsis can be used to indicate a breakpoint or a place where code execution has been paused.

import pdb; pdb.set_trace()

After hitting this line during execution, you can interact with the debugger prompt.

Do comment if you have any doubts or suggestions on this Python topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading