I'd suggest using bisect
from bisect import bisect class Element(object): def __init__(self, value): self.a = value def __repr__(self): return 'Element({})'.format(self.a) data = [Element(3), Element(5), Element(7), Element(1)] last = 0 breakpoints = [] for element in data: breakpoints.append(last + element.a) last += element.a print(breakpoints) for random_value in xrange(last): pos = bisect(breakpoints, random_value) print(random_value, data[pos])
You have to build the list with the breakpoints just once. Then you can use it with the pretty fast bisect algorithm as long as you like.
The last loop is just to demonstrate the result.
Edit: An alternative approach to get the breakpoints (I didn't like the for-loop):
values = [value.a for value in data] breakpoints = [sum(values[:pos+1]) for pos in xrange(len(values))]