CodexBloom - Programming Q&A Platform

best practices for 'TypeError: unhashable type: 'list'' when using sets in Python?

👀 Views: 1594 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-10
python sets data-structures Python

I'm not sure how to approach Does anyone know how to I tried several approaches but none seem to work... I'm working with 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 behavior mentioned above. I understand that lists are mutable and want to be hashed, which is causing the scenario 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 behavior, 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! For context: I'm using Python on macOS. Has anyone else encountered this? I'm using Python 3.11 in this project. Am I approaching this the right way? I'm using Python 3.10 in this project. Cheers for any assistance! This is my first time working with Python LTS. Thanks, I really appreciate it!