insert

iteration_utilities.insert(iterable, element, idx, unpack=False)

Insert one element into iterable.

Parameters:
iterableiterable

The iterable in which to insert the element.

elementany type

The element to insert to the iterable.

idxpositive int or str

The index at which to insert the element. If it’s a string it must be 'start' if the element should be prepended to iterable or 'end' if it should be appended.

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:
insertedgenerator

The element inserted into iterable at idx as generator.

Examples

To prepend a value:

>>> from iteration_utilities import insert
>>> list(insert(range(10), 100, 'start'))  # 'start' is equivalent to 0
[100, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

To append a value:

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

Or to insert it at a given index:

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

It is also possible to unpack another iterable into another one with the unpack argument:

>>> list(insert(range(10), [1, 2, 3], 0, unpack=True))
[1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If the unpack argument is not given the iterable is inserted as it is:

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