replace

iteration_utilities.replace(iterable, element, idx=None, start=None, stop=None, unpack=False)

Removes the item at idx or from start (inclusive) to stop (exclusive) and then inserts the element there.

Parameters:
iterableiterable

The iterable in which to replace the item(s).

elementany type

The element to insert after removing.

idxpositive int, list/tuple thereof, None, optional

If not None, remove the item at idx and insert element there. If it’s a tuple or list the element is inserted at each of the indices in the idx (the values are sorted before, so the element is always inserted at the given indices). Default is None.

Note

This parameter must not be None if also start and stop are None.

startpositive int or None, optional

If None then remove all items before stop, otherwise remove only the items starting by start. Default is None.

Note

This parameter is ignored if idx is not None.

stoppositive int or None, optional

If None then remove all items starting by start, otherwise only remove the items before stop. Default is None.

Note

This parameter is ignored if idx is not None.

unpackbool, optional

If False the element is inserted as it is. If True then the element must be an iterable and it is unpacked into the iterable. Default is False.

Returns:
replacedgenerator

The iterable with the specified items removed and element inserted in their place.

Examples

To replace one item:

>>> from iteration_utilities import replace
>>> list(replace(range(10), 100, idx=2))
[0, 1, 100, 3, 4, 5, 6, 7, 8, 9]

To replace multiple items:

>>> list(replace(range(10), 100, (3, 5, 1)))
[0, 100, 2, 100, 4, 100, 6, 7, 8, 9]

To replace slices:

>>> list(replace(range(10), 100, start=2))
[0, 1, 100]

>>> list(replace(range(10), 100, stop=2))
[100, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list(replace(range(10), 100, start=2, stop=5))
[0, 1, 100, 5, 6, 7, 8, 9]