How to flatten a 2D list into a sorted one-dimensional list with unique values in Python

1 Answer

0 votes
# Function that flattens a 2D list, sorts it, and removes duplicates,
# and returns a new sorted list with unique values
def flatten_sort_unique(lst2d: list[list[int]]) -> list[int]:

    # 1. Flatten the 2D list into a 1D list
    flat: list[int] = []
    for row in lst2d:
        flat.extend(row)

    # 2. Sort the flattened list
    flat.sort()

    # 3. Remove duplicates using a set, then convert back to a sorted list
    unique: list[int] = sorted(set(flat))

    return unique


# Input list 
lst2d: list[list[int]] = [
    [4, 3, 3, 2, 4],
    [30, 10, 10],
    [10, 30],
    [1, 1, 6, 7, 7, 7, 8],
]

lst: list[int] = flatten_sort_unique(lst2d)

# Print results
for n in lst:
    print(n, end="\t")


"""
run

1   2   3   4   6   7   8   10   30

"""

 



answered 3 hours ago by avibootz
edited 3 hours ago by avibootz

Related questions

...