summaryrefslogtreecommitdiff
path: root/list_utils.py
blob: 74f1cf3078457d371194deb33ddf5ad6410ed599 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/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:])