summaryrefslogtreecommitdiff
path: root/list_utils.py
blob: 7d3355cc85a72a047aacaa0c3f06430a9e8e8dd7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env python3

from itertools import islice
from typing import Any, Iterator, List


def shard(lst: List[Any], size: int) -> Iterator[Any]:
    """Yield successive size-sized shards from lst."""
    for x in range(0, len(lst), size):
        yield islice(lst, x, x + size)


def flatten(lst: List[Any]) -> List[Any]:
    """Flatten out a list:

        >>> flatten([ 1, [2, 3, 4, [5], 6], 7, [8, [9]]])
        [1, 2, 3, 4, 5, 6, 7, 8, 9]
    """
    if len(lst) == 0:
        return lst
    if isinstance(lst[0], list):
        return flatten(lst[0]) + flatten(lst[1:])
    return lst[:1] + flatten(lst[1:])


def prepend(item: Any, lst: List[Any]) -> List[Any]:
    """Prepend an item to a list."""
    lst = list.insert(0, item)
    return lst