Reputation: 573
I have the following code in Python:
import numpy as np
arr = numpy.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
print(arr[::-1]) # reverses the array
print(arr[:,::-1] # reverses the array in the second dimension
print(arr[:,:,::-1] # reverses the array in the third dimension,i.e. all elements
print(arr[...,::-1]# gives the same output as above line
Output:
array([[[7,8,9],[10,11,12]],[[1,2,3],[4,5,6]]])
array([[[4,5,6],[1,2,3]],[[10,11,12],[7,8,9]]])
array([[[3,2,1],[6,5,4]],[[9,8,7],[12,11,10]]])
array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
now, i wanna know what is arr[...] as it prints the whole list as it is,but is working in a different way for thefinal print statement. And, why doesn't the same syntax work on python lists.
Also, even though this shall not be the part of the question am somewhat curious to learn that if i were to implement the same fucnitonality for one of my class objects how would i do..?
Upvotes: 0
Views: 56
Reputation: 231530
In arr[..., ::-1]
the ...
stands for a variable number of :
, hence the last 2 cases just reverse the last dimension.
arr[...]
is the same as arr[:]
, a view
without change.
Lists only have one level of indexing, so alist[:]
and alist[::-1]
work, but nothing which a comma, or the ellipsis. Sublists in a nested list have to have their own indexing.
alist[:] # a copy
alist[::-1] # a reverse copy
these also work for strings
In [187]: 'astring'[:]
Out[187]: 'astring'
In [188]: 'astring'[::-1]
Out[188]: 'gnirtsa'
Basic reference for numpy indexing:
https://numpy.org/doc/stable/reference/arrays.indexing.html
a start for python sequence indexing (for lists and strings)
https://docs.python.org/3/library/stdtypes.html#common-sequence-operations
I'm more familiar with numpy
documentation, since I learned python basics too long ago. List indexing should be well covered in any Python intro book.
Upvotes: 1