In [1]:
import itertools

In [2]:
l_2d = [[0, 1], [2, 3]]

In [3]:
print(list(itertools.chain.from_iterable(l_2d)))


[0, 1, 2, 3]

In [4]:
t_2d = ((0, 1), (2, 3))

In [5]:
print(tuple(itertools.chain.from_iterable(t_2d)))


(0, 1, 2, 3)

In [6]:
l_3d = [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]

In [7]:
print(list(itertools.chain.from_iterable(l_3d)))


[[0, 1], [2, 3], [4, 5], [6, 7]]

In [8]:
l_mix = [[0, 1], [2, 3], 4]

In [9]:
# print(list(itertools.chain.from_iterable(l_mix)))
# TypeError: 'int' object is not iterable

In [10]:
print(sum(l_2d, []))


[0, 1, 2, 3]

In [11]:
# print(sum(l_2d))
# TypeError: unsupported operand type(s) for +: 'int' and 'list'

In [12]:
print(sum(t_2d, ()))


(0, 1, 2, 3)

In [13]:
print(sum(l_3d, []))


[[0, 1], [2, 3], [4, 5], [6, 7]]

In [14]:
# print(sum(l_mix, []))
# TypeError: can only concatenate list (not "int") to list

In [15]:
import collections

In [16]:
def flatten(l):
    for el in l:
        if isinstance(el, collections.abc.Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el

In [17]:
print(list(flatten(l_2d)))


[0, 1, 2, 3]

In [18]:
print(list(flatten(l_3d)))


[0, 1, 2, 3, 4, 5, 6, 7]

In [19]:
print(list(flatten(l_mix)))


[0, 1, 2, 3, 4]

In [20]:
l_t_r_mix = [[0, 1], (2, 3), 4, range(5, 8)]

In [21]:
print(list(flatten(l_t_r_mix)))


[0, 1, 2, 3, 4, 5, 6, 7]

In [22]:
def flatten_list(l):
    for el in l:
        if isinstance(el, list):
            yield from flatten_list(el)
        else:
            yield el

In [23]:
print(list(flatten_list(l_2d)))


[0, 1, 2, 3]

In [24]:
print(list(flatten_list(l_3d)))


[0, 1, 2, 3, 4, 5, 6, 7]

In [25]:
print(list(flatten_list(l_mix)))


[0, 1, 2, 3, 4]

In [26]:
print(list(flatten_list(l_t_r_mix)))


[0, 1, (2, 3), 4, range(5, 8)]

In [27]:
def flatten_list_tuple_range(l):
    for el in l:
        if isinstance(el, (list, tuple, range)):
            yield from flatten_list_tuple_range(el)
        else:
            yield el

In [28]:
print(list(flatten_list_tuple_range(l_t_r_mix)))


[0, 1, 2, 3, 4, 5, 6, 7]