Initial revision
[python_utils.git] / list_utils.py
1 #!/usr/bin/env python3
2
3 from itertools import islice
4 from typing import Any, Iterator, List
5
6
7 def shard(lst: List[Any], size: int) -> Iterator[Any]:
8     """Yield successive size-sized shards from lst."""
9     for x in range(0, len(lst), size):
10         yield islice(lst, x, x + size)
11
12
13 def flatten(lst: List[Any]) -> List[Any]:
14     """Flatten out a list:
15
16         >>> flatten([ 1, [2, 3, 4, [5], 6], 7, [8, [9]]])
17         [1, 2, 3, 4, 5, 6, 7, 8, 9]
18
19     """
20     if len(lst) == 0:
21         return lst
22     if isinstance(lst[0], list):
23         return flatten(lst[0]) + flatten(lst[1:])
24     return lst[:1] + flatten(lst[1:])