batlike
batlike

Reputation: 698

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 [()]?

Upvotes: 0

Views: 171

Answers (2)

DeepSpace
DeepSpace

Reputation: 81594

() is an empty tuple, and indexing with an empty tuple is documented in h5py's documentation:

An empty dataset has shape defined as None, which is the best way of determining whether > a dataset is empty or not. An empty dataset can be “read” in a similar way to scalar > datasets, i.e. if empty_dataset is an empty dataset,:

>>> empty_dataset[()]
h5py.Empty(dtype="f")

The dtype of the dataset can be accessed via .dtype as per normal. As empty > datasets cannot be sliced, some methods of datasets such as read_direct will raise an exception if used on a empty dataset.

Upvotes: 0

hobbs
hobbs

Reputation: 239771

() 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.

Upvotes: 1

Related Questions