Iterable tools

Functions

get_first_of_iterable(iterable)

Return the first element of the given sequence.

ichunk_iterable(iterable[, chunk_length])

Split a sequence into consecutive sub-sequences of given length by returning a generator of generators generating the sub sequences.

is_empty_iterable(iterable)

Check if a sequence is empty.

split(iterable, function)

Split an iterable into two lists according to test function

unzip(zipped)

Unzip a zipped list

split(iterable, function)

Split an iterable into two lists according to test function

Parameters
  • iterable (iterable) – iterable of values to be split

  • function (function) – decision function value => bool

Returns

tuple( list with values for which function is True, list with values for which function is False,)

Example

>>> split([1,2,3,4,5,6], lambda x: x<3)
([1, 2], [3, 4, 5, 6])
unzip(zipped)

Unzip a zipped list

Parameters

zipped (list-of-tuple) – list of tuples to be disaggregated

Returns

list of tuples

Example

>>> unzip([(1, 2, 3), (4, 5, 6), (7, 8, 9)])
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
is_empty_iterable(iterable)

Check if a sequence is empty.

Most useful on generator types.

Parameters

iterable (iterable) – input iterable

Returns

tuple(iterable, is_empty). If a generator is passed, a new generator will be returned preserving the original values

Example

>>> a = []
>>> b = (str(i) for i in range(0))
>>> c = (str(i) for i in range(5))
>>> a, is_empty = is_empty_iterable(a)
>>> a, is_empty
([], True)
>>> b, is_empty = is_empty_iterable(b)
>>> is_empty
True

When the generator c is given, a new generator is returned by is_empty_iterable to preserve original values of c:

>>> c, is_empty = is_empty_iterable(c)
>>> next(c), is_empty
('0', False)
get_first_of_iterable(iterable)

Return the first element of the given sequence.

Most useful on generator types.

Parameters

iterable (iterable) – input iterable

Returns

tuple(iterable, first_element). If a generator is passed, a new generator will be returned preserving the original values.

Raises

IndexError

Example

>>> a = [1,2,3]
>>> b = (str(i) for i in range(3))
>>> a, first_element = get_first_of_iterable(a)
>>> a, first_element
([1, 2, 3], 1)

When the generator b is given, a new generator is returned by is_empty_iterable to preserve original values of b:

>>> b, first_element = get_first_of_iterable(b)
>>> next(b), first_element
('0', '0')
ichunk_iterable(iterable, chunk_length=4096)

Split a sequence into consecutive sub-sequences of given length by returning a generator of generators generating the sub sequences.

Most useful on generator types.

Parameters
  • iterable (iterable) – input iterable

  • chunk_length (int?) – length of the chunks. (default: 4096)

Generates

generators

Example

>>> iterable = range(15)
>>> chunks = ichunk_iterable(iterable, 4)
>>> for chunk in chunks:
>>>    print(list(chunk))
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
[12, 13, 14]