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

How to add a tuple which consisting of a list and a string itself into a set in python?

I want to insert multiple tuples into a set which each tuple contains a list and a string.
Each tuple looks like:

sample_tuple = (['list of elements'], 'one_string')

If we check the type of sample_tuple, we can be sure that it is a tuple with 2 elements (one list and one string).
But when I use the "add" method to insert this tuple to my set, I get the error:

    TypeError                                 Traceback (most recent call last)
    c:\run.ipynb Cell 47 in <cell line: 15>()
         11 sample_tuple = (['list of elements'], 'one_string')
         12 sample_set.add(sample_tuple)

TypeError: unhashable type: 'list'

But this is the way that I insert a tuple into a set in python.
Is there a way I can keep the form of my tuple (ie my tuple still consists of a list and a string) and then be able to insert this tuple into a set in Python?

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 :

Set members must be hashable.
That’s the way Python ensures that members are unique.
Lists in Python are not hashable (because lists are mutable meaning you can update one item of the list).

hash([1])  # Error!

If you don’t intent to mutate your sequence of elements, prefer using a tuple that is unmutable and hashable.

sample_tuple = (('tuple of elements'), 'one_string')
sample_set = set()
sample_set.add(sample_tuple)
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