There's also some function in itertools to do this exact thing.