split

class iteration_utilities.split(iterable, key, maxsplit=-1, keep=False, keep_before=False, keep_after=False, eq=False)

Splits an iterable by a key function or delimiter.

Parameters:
iterableiterable

The iterable to split.

keycallable

The function by which to split the iterable (split where key(item) == True).

maxsplitint, optional

The number of maximal splits. If maxsplit=-1 then there is no limit. Default is -1.

keepbool

If True also include the items where key(item)=True as separate list. Default is False.

keep_beforebool

If True also include the items where key(item)=True in the list before splitting. Default is False.

keep_afterbool

If True also include the items where key(item)=True as first item in the list after splitting. Default is False.

eqbool

If True split the iterable where key == item instead of key(item) == True. This can significantly speed up the function if a single delimiter is used. Default is False.

Returns:
splitted_iterablegenerator

Generator containing the splitted iterable (lists).

Raises:
TypeError

If maxsplit is smaller than -2. If more than one of the keep arguments is True.

Examples

>>> from iteration_utilities import split
>>> list(split(range(1, 10), lambda x: x%3==0))
[[1, 2], [4, 5], [7, 8]]
>>> list(split(range(1, 10), lambda x: x%3==0, keep=True))
[[1, 2], [3], [4, 5], [6], [7, 8], [9]]
>>> list(split(range(1, 10), lambda x: x%3==0, keep_before=True))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> list(split(range(1, 10), lambda x: x%3==0, keep_after=True))
[[1, 2], [3, 4, 5], [6, 7, 8], [9]]
>>> list(split(range(1, 10), lambda x: x%3==0, maxsplit=1))
[[1, 2], [4, 5, 6, 7, 8, 9]]
>>> list(split([1,2,3,4,5,3,7,8,3], 3, eq=True))
[[1, 2], [4, 5], [7, 8]]
eq

(bool) Instead of calling key compare the items with it (readonly).

New in version 0.6.

keep

(bool) Keep the delimiter (readonly).

New in version 0.6.

keep_after

(bool) Keep the delimiter as first item of the next group (readonly).

New in version 0.6.

keep_before

(bool) Keep the delimiter as last item of the last group (readonly).

New in version 0.6.

key

(callable or any type) The function or value by which to split (readonly).

New in version 0.6.

maxsplit

(int) The number of maximum splits (readonly).

New in version 0.6.