Ashish Dhamu
Ashish Dhamu

Reputation: 71

What is the use of ellipsis in Python?

What is the use of ellipsis (...) in Python with some examples and when to use it?

I have done some search on this; it can be used with a function:

 def add():
     ...

and with slicing in the list.

import numpy
n = numpy.arange(16).reshape(2, 2, 2, 2)

print(n)

print('----------------')
print(n[1,...,1])

[[[[ 0  1]
   [ 2  3]]

  [[ 4  5]
   [ 6  7]]]


 [[[ 8  9]
   [10 11]]

  [[12 13]
   [14 15]]]]
----------------
Ellipsis:[[ 9 11]
 [13 15]]

Upvotes: 4

Views: 5964

Answers (1)

Masklinn
Masklinn

Reputation: 42197

Originally the ellipsis literal (that's what ... is) was very restricted, in Python 2 it could essentially only be used as a sentinel when slicing, and what it would do specifically was not prescriptive and was entirely defined by how the container would react (I don't think any of the standard library containers handled ellipsis, so it was mostly for numpy).

In Python 3 the ellipsis operator was relaxed somewhat, the old usage stays but it has also gained a new use as a less verbose version of pass, which is also a traditional "longhand" use of ellipsis, when you either don't care what a function body is or haven't come to fill it yet, you can just put in ... instead of pass, it's basically a no-op but it looks a bit better / less noisy:

def do_foo():
    pass

versus

def do_foo():
    ...

Upvotes: 6

Related Questions