Can't you use something from `itertools` here?