Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use the ellipsis slicing syntax in Python?

This came up in Hidden features of Python, but I can't see good documentation or examples that explain how the feature works.

like image 419
miracle2k Avatar asked Sep 23 '08 00:09

miracle2k


People also ask

How do you use ellipsis in Python?

Ellipsis is a Python Object. It has no Methods. It is a singleton Object i.e, provides easy access to single instances.

What is ellipsis in NumPy?

In NumPy, you can use Ellipsis ( ... ) to omit intermediate dimensions when specifying elements or ranges with [] .

How does slicing an array work in Python?

Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end] . We can also define the step, like this: [start:end:step] .

Is slicing inclusive Python?

Slicing Values. Python is a zero-indexed language (things start counting from zero), and is also left inclusive, right exclusive you are when specifying a range of values. This applies to objects like lists and Series , where the first element has a position (index) of 0.


2 Answers

The ellipsis is used in numpy to slice higher-dimensional data structures.

It's designed to mean at this point, insert as many full slices (:) to extend the multi-dimensional slice to all dimensions.

Example:

>>> from numpy import arange >>> a = arange(16).reshape(2,2,2,2) 

Now, you have a 4-dimensional matrix of order 2x2x2x2. To select all first elements in the 4th dimension, you can use the ellipsis notation

>>> a[..., 0].flatten() array([ 0,  2,  4,  6,  8, 10, 12, 14]) 

which is equivalent to

>>> a[:,:,:,0].flatten() array([ 0,  2,  4,  6,  8, 10, 12, 14]) 

In your own implementations, you're free to ignore the contract mentioned above and use it for whatever you see fit.

like image 170
Torsten Marek Avatar answered Nov 13 '22 23:11

Torsten Marek


Ellipsis, or ... is not a hidden feature, it's just a constant. It's quite different to, say, javascript ES6 where it's a part of the language syntax. No builtin class or Python language constuct makes use of it.

So the syntax for it depends entirely on you, or someone else, having written code to understand it.

Numpy uses it, as stated in the documentation. Some examples here.

In your own class, you'd use it like this:

>>> class TestEllipsis(object): ...     def __getitem__(self, item): ...         if item is Ellipsis: ...             return "Returning all items" ...         else: ...             return "return %r items" % item ...  >>> x = TestEllipsis() >>> print x[2] return 2 items >>> print x[...] Returning all items 

Of course, there is the python documentation, and language reference. But those aren't very helpful.

like image 41
nosklo Avatar answered Nov 13 '22 23:11

nosklo