What is Three dots(…) or Ellipsis in Python3
Ellipsis is a Python Object. It has no Methods. It is a singleton Object i.e, provides easy access to single instances.
Various Use Cases of Ellipsis (…):
- Default Secondary Prompt in Python interpreter.
- Accessing and slicing multidimensional Arrays/NumPy indexing.
- In type hinting.
- Used as Pass Statement inside Functions.
Default Secondary Prompt in Python interpreter
Ellipsis notation[…] is used as a default secondary prompt in Python interpreter which is seen during multi-line constructs
Accessing and slicing multidimensional Arrays/NumPy indexing
- Accessing: Giving access to a specified range of elements, just omitting out the serial indices.
- Slicing: Important use of Ellipsis is in slicing higher-dimensional data structures.
Suppose, we have a 4-dimensional matrix of order 2x2x2x2. To select all first row elements(in case of row-major structure) in the 4th dimension, we can simply use the ellipsis notation
[[[0.46253663 0.03092289] [0.72723607 0.75953107]] [[0.33160093 0.79259324] [0.76757812 0.21241883]]] [[[0.46253663 0.03092289] [0.72723607 0.75953107]] [[0.33160093 0.79259324] [0.76757812 0.21241883]]]
In the above example, [:, :, :, 0], […, 0] and [Ellipsis, 0] are all equivalent.
We can not have multiple ellipsis in a single slicing like a[…,index,…]
In type hinting
Ellipsis is used in specifying type hints using the typing module (e.g. Callable[…, str]). It can serve in either way:
Method 1: When the argument(s) of the function allows the type: Any
Actually callable takes the arguments:
Callable "[" parameters_expression, type_expression "]"
(e.g. Callable[…, str])
Using ‘…’ as parameters_expression signifies a function that returns a string without specifying the call signature.
Method 2: When the return value of the function is of type: Any
Actually callable returns this way:
Callable "[" parameters_expression, type_expression "]" -> return_type: #body
Used as Pass Statement inside Functions
Ellipsis is used instead of pass statement inside functions. ‘pass’ replaced by ‘…’ or ‘Ellipsis’.
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.
<function foo at 0x7fabdeea6e18>
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course