hum, you may want to look in the itertools modules. I am pretty sure they have a function to do what you are doing.