For every use I can think of for Python’s itertools.repeat() class, I can think of another equally (possibly more) acceptable solution to achieve the same effect. For example:
>>> [i for i in itertools.repeat('example', 5)]
['example', 'example', 'example', 'example', 'example']
>>> ['example'] * 5
['example', 'example', 'example', 'example', 'example']
>>> list(map(str.upper, itertools.repeat('example', 5)))
['EXAMPLE', 'EXAMPLE', 'EXAMPLE', 'EXAMPLE', 'EXAMPLE']
>>> ['example'.upper()] * 5
['EXAMPLE', 'EXAMPLE', 'EXAMPLE', 'EXAMPLE', 'EXAMPLE']
Is there any case in which itertools.repeat() would be the most appropriate solution? If so, under what circumstances?
The
itertools.repeatfunction is lazy; it only uses the memory required for one item. On the other hand, the(a,) * nand[a] * nidioms create n copies of the object in memory. For five items, the multiplication idiom is probably better, but you might notice a resource problem if you had to repeat something, say, a million times.Still, it is hard to imagine many static uses for
itertools.repeat. However, the fact thatitertools.repeatis a function allows you to use it in many functional applications. For example, you might have some library functionfuncwhich operates on an iterable of input. Sometimes, you might have pre-constructed lists of various items. Other times, you may just want to operate on a uniform list. If the list is big,itertools.repeatwill save you memory.Finally,
repeatmakes possible the so-called “iterator algebra” described in theitertoolsdocumentation. Even theitertoolsmodule itself uses therepeatfunction. For example, the following code is given as an equivalent implementation ofitertools.izip_longest(even though the real code is probably written in C). Note the use ofrepeatseven lines from the bottom: