Skip to content

Histogram python __len__ inconsistent with __getitem__ #19311

@Zehvogel

Description

@Zehvogel

Check duplicate issues.

  • Checked for duplicates

Description

For a particular use case, I want to obtain the contents of a histogram h as a Python list. I saw that len(h) and h[i] work, so I tried out list(h), which throws an IndexError from the UHI pythonizations. I guess due to the fact that __len__ returns the length with the under-/overflow bins and __getitem__ from UHI ignores them on purpose, as I understand?

Reproducer

import ROOT
h = ROOT.TH1D("", "", 3, 0., 1.)
len(h)
# 5
h[0]
# 0.0
list(h)
# IndexError
h[3]
# same IndexError
h[4]
# 0.0 again funnily :)

ROOT version

   ------------------------------------------------------------------
  | Welcome to ROOT 6.37.01                        https://root.cern |
  | (c) 1995-2025, The ROOT Team; conception: R. Brun, F. Rademakers |
  | Built for linuxx8664gcc on Jul 07 2025, 22:55:31                 |
  | From heads/master@v6-37-01-7334-ga481509823                      |
  | With clang version 16.0.3                                        |
  | Try '.help'/'.?', '.demo', '.license', '.credits', '.quit'/'.q'  |
   ------------------------------------------------------------------

Installation method

source /cvmfs/sft.cern.ch/lcg/views/dev3/latest/x86_64-el9-clang16-opt/setup.sh

Operating system

Alma9

Additional context

Workaround:

[h[i] for i in range(h.GetNbinsX())]

Metadata

Metadata

Labels

Type

No type

Projects

Status

No status

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions