Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

different behaviour of unhashable typeError between cpp and python

It is ok to insert a vector to a set in cpp, which not works in python however. Codes shown below:

// OK in cpp
set<vector<int>> cpp_set;
cpp_set.insert(vector<int>{1,2,3});

// not OK in python
py_set = set()
py_set.add([1,2,3])  # TypeError: unhashable type: 'list'
py_set.add({1,2,3})  # TypeError: unhashable type: 'set'

Even adding a set to a set is not allowed, and I don’t understand why a set is unhashable.

Why does the difference happens? And is it a permitted good way to use in cpp? I mean adding a vector to a set.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Python’s set is a hash table, and has no hashing functions for set and list.

std::set is not a hash table but a sequence ordered by an ordering relation (std::less by default).
You can use std::set with any type where you can define a strict weak ordering.

Try std::unordered_set in C++ and you will encounter problems.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading