[lang-ref] ( flatten ) ( python )

def test_flatten():
    # comprehension
    rows = [[1, 2], [3, 4, 5], [6, 7]]
    expected = [1, 2, 3, 4, 5, 6, 7]
    actual   = [x for row in rows for x in row]

    assert actual == expected
def test_flatten_alternative1():
    # chain.from_iterable
    from itertools import chain

    rows = [[1, 2], [3, 4, 5], [6, 7]]
    expected = [1, 2, 3, 4, 5, 6, 7]
    actual   = list(chain.from_iterable(rows))

    assert actual == expected
def test_flatten_alternative2():
    # reduce
    from functools import reduce

    rows = [[1, 2], [3, 4, 5], [6, 7]]
    expected = [1, 2, 3, 4, 5, 6, 7]
    actual   = reduce(lambda acc, row: acc + row, rows)

    assert actual == expected