4

Could someone please help, what is the use of Ellipse 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]]
Logica
  • 977
  • 4
  • 16
Ashish Dhamu
  • 71
  • 1
  • 4
  • Does this answer your question? [How do you use the ellipsis slicing syntax in Python?](https://stackoverflow.com/questions/118370/how-do-you-use-the-ellipsis-slicing-syntax-in-python) – Masklinn Feb 24 '20 at 07:26

1 Answers1

6

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():
    ...
Masklinn
  • 34,759
  • 3
  • 38
  • 57
  • could you please help me with the list example also – Ashish Dhamu Feb 24 '20 at 07:18
  • That's the first part, it's a slice and what happens is whatever numpy wants to do with it, [which numpy documents](https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html#basic-slicing-and-indexing) "Ellipsis expand to the number of : objects needed to make a selection tuple of the same length as x.ndim.". See also https://stackoverflow.com/questions/118370/how-do-you-use-the-ellipsis-slicing-syntax-in-python – Masklinn Feb 24 '20 at 07:26
  • Although some are doing this, it's probably better to just use `pass` since there is no official documentation around using `Ellipsis`. – Alex W Feb 01 '22 at 17:32
  • a complete answer should also address numpy's m[..., 0] for instance, and also what is means in an import statement (which is what I came here looking for). – TamaMcGlinn May 09 '22 at 09:00