Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma index in python list bracket

Tags:

python

example is below. What is this? A comma is in the python list-bracket. How can I understand this?

id(x[i,j]) == id(x[i][j]) shows True.

So, x[i,j] is always same at x[i][j]?

or, x[i,j] is actually same as x[(i,j)]? index is tuple.

import numpy as np
x = np.random.random((64,3,32,10))
for i in range(x.shape[0]):
    for j in range(x.shape[1]):
        print(x[i,j])

======
I guess this is numpy's special implementation. Numpy overwrites "_getitem__" function for using tuple index.

I tried it for
1) basic python
2) overwrite "_getitem__ " and
3) basic numpy.

1) shows error. "TypeError: list indices must be integers or slices, not tuple"
2) has....no problem if I implemented right.
3) just works well.

So, I guess numpy developers did implemented their "getitem" function for tuple, and it works same arr[x,y,z] == arr[x][y][z].


1 Answers

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.

like image 145
David Wolever Avatar answered Nov 19 '25 17:11

David Wolever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!