Code Implementation
Python
def flatten_unique(nested_list):
return list(set([item for sublist in nested_list for item in sublist]))
# Usage
nested = [[1, 2], [2, 3], [4]]
print(flatten_unique(nested)) # [1, 2, 3, 4]
Flatten a 2D list (list of lists) into a 1D list and remove duplicate elements.
Snippet Description
- Use list comprehension for quick flattening
- Use
set
to remove duplicates (output is unordered); for ordered output, use thedict.fromkeys
trick
Recommended Snippets
Python Remove Duplicates from List of Dicts
Remove duplicates from a list of dictionaries based on a specific key in the dictionaries.
Python
#dict+1
6
0
Python Read Nested JSON File Example
How to read JSON files with nested structures in Python and safely access deep-level fields.
Python
#json+1
8
0
Python: Write Dict to CSV with Headers
Write a list of dictionaries to a CSV file and automatically generate headers.
Python
#dict+1
6
0
Comments
Loading...