Home >Backend Development >Python Tutorial >How Can I Efficiently Deduplicate a List of Lists While Maintaining Order?
Given a list of lists, the goal is to eliminate duplicate elements while preserving order. While converting lists to tuples to leverage sets would be straightforward, it's inefficient.
itertools offers a remarkable solution:
import itertools k.sort() list(k for k,_ in itertools.groupby(k))
This approach excels by:
Extensive benchmarking reveals that "groupby" generally outperforms other methods for large input lists. However, for tiny lists with few duplicates, the "loop in" approach might be slightly faster.
When performance is paramount, consider:
The above is the detailed content of How Can I Efficiently Deduplicate a List of Lists While Maintaining Order?. For more information, please follow other related articles on the PHP Chinese website!