CodexBloom - AI-Powered Q&A Platform

How to resolve 'TypeError: unhashable type: 'list'' when using sets in Python?

👀 Views: 2 💬 Answers: 1 📅 Created: 2025-06-10
python sets data-structures

I'm encountering a `TypeError: unhashable type: 'list'` when trying to use a set to store unique lists in my Python code. I'm currently using Python 3.9. I have a list of lists that I want to convert into a set to automatically filter out duplicates. Here's the code I've been working with: ```python lists = [[1, 2], [3, 4], [1, 2], [5, 6]] unique_lists = set(lists) ``` When I run this, I get the error mentioned above. I understand that lists are mutable and cannot be hashed, which is causing the issue when I attempt to create a set from a list of lists. I've tried converting each inner list to a tuple before adding them to the set: ```python unique_lists = set(tuple(lst) for lst in lists) ``` This works without throwing an error, but I'm not sure if this is the best practice. It feels a bit inelegant, especially if the original lists may contain complex objects or nested structures. Additionally, I'm concerned about how this will impact performance if the lists become very large. Is there a more efficient or Pythonic approach to achieving a unique set of lists? How can I ensure this method scales well with larger datasets? Any advice or best practices would be greatly appreciated!