File: flatten.py

package info (click to toggle)
python-schema-salad 2.2.20170111180227-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 3,168 kB
  • ctags: 213
  • sloc: python: 2,991; makefile: 138
file content (26 lines) | stat: -rw-r--r-- 562 bytes parent folder | download | duplicates (2)
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
import sys
from typing import Any, Tuple

# http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html


def flatten(l, ltypes=(list, tuple)):
    # type: (Any, Any) -> Any
    if l is None:
        return []
    if not isinstance(l, ltypes):
        return [l]

    ltype = type(l)
    l = list(l)
    i = 0
    while i < len(l):
        while isinstance(l[i], ltypes):
            if not l[i]:
                l.pop(i)
                i -= 1
                break
            else:
                l[i:i + 1] = l[i]
        i += 1
    return ltype(l)