intersperse

class iteration_utilities.intersperse(iterable, e)

Alternately yield an item from the iterable and e. Recipe based on the homonymous function in the more-itertools package ([0]) but significantly modified.

Parameters:
iterableiterable

The iterable to intersperse.

eany type

The value with which to intersperse the iterable.

Returns:
interspersedgenerator

Interspersed iterable as generator.

Notes

This is similar to itertools.chain.from_iterable(zip(iterable, itertools.repeat(e))) except that intersperse does not yield e as last item.

References

Examples

A few simple examples:

>>> from iteration_utilities import intersperse
>>> list(intersperse([1,2,3], 0))
[1, 0, 2, 0, 3]

>>> list(intersperse('abc', 'x'))
['a', 'x', 'b', 'x', 'c']
__length_hint__()

Tries to estimate for the length of the instance (returns 0 if an estimation is not possible).

fillvalue

(any type) The interspersed fillvalue (readonly).

New in version 0.6.