The Python Oracle

Comma index in python list bracket

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping

--

Chapters
00:00 Question
01:38 Accepted answer (Score 1)
02:07 Answer 2 (Score 4)
02:48 Thank you

--

Full question
https://stackoverflow.com/questions/5452...

Accepted answer links:
[Numpy official docs]: https://docs.scipy.org/doc/numpy-1.13.0/...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ANSWER 1

Score 4


While numpy behaves the same way with the two, they are technically different.

You can see the difference by implementing __getitem__ yourself:

class GetitemTest(object):
    def __getitem__(self, item):
        print("getting: %r" %(item, ))
        return self

Then:

>>> x = GetitemTest()
>>> x[1,2]
getting: (1, 2)
<__main__.GetitemTest object at 0x10bb6d810>

>>> x[1][2]
getting: 1
getting: 2
<__main__.GetitemTest object at 0x10bb6d810>

Notice that x[1,2] only calls __getitem__ once, but x[1][2] calls it twice.




ACCEPTED ANSWER

Score 1


This is Numpy special ability.
Numpy official docs
"Unlike lists and tuples, numpy arrays support multidimensional indexing for multidimensional arrays. That means that it is not necessary to separate each dimension’s index into its own set of square brackets."

>>> x.shape = (2,5) # now x is 2-dimensional
>>> x[1,3]
8
>>> x[1,-1]
9