Python and ROOT Tricks: I need more range!

When you’re writing a Python program to loop over a large number of events, for instance those stored in a large ROOT TChain object [1], you may find that the standard bit of help on the web is not sufficient:

TChain aChain("NameOfTTree")
aChain.Add("/a/bunch/of/files/*.root")
for anEvent in range(aChain.GetEntries()):
    # Do a bunch of stuff with an event in a TTree

If there are too many events for the Python range() function – that is, if the integer returned by the TChain::GetEntries() method is too big for Python – you’ll get an error. Now how are you going to run over these events?

One way to handle this is to use the xrange() function instead of range(); it can handle a much larger integer and generate a much larger list of integer events:

TChain aChain("NameOfTTree")
aChain.Add("/a/bunch/of/files/*.root")
for anEvent in xrange(aChain.GetEntries()):
    # Do a bunch of stuff with an event in a TTree

[1] http://root.cern.ch/root/html/TChain.html

Print Friendly, PDF & Email

One Reply to “Python and ROOT Tricks: I need more range!”

Leave a Reply

Your email address will not be published. Required fields are marked *