Search code examples
python-3.xhdf5

What is the meaning of () inside a list eg. [()] in Python?


I came across an h5py tutorial wherein a particular index of an hdf5 file is accessed as follows:

f = h5py.File('random.hdf5', 'r')
data = f['default'][()]
f.close()

print(data[10])

In this manner, even when the file is closed, the data is still accessible. It seems adding [()] no longer makes data a simple pointer, but rather the data object itself. What is the meaning of [()]?


Solution

  • () is an empty tuple. HDF5 datasets can have an arbitrary number of dimensions and support indexing, but some datasets are zero-dimensional (they store a single scalar value). For these, h5py uses indexing with an empty tuple [()] to access that value. You can't use [0] or even [:] because that implies at least one dimension to slice along.