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

Time:11-10

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?

CodePudding user response:

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)

CodePudding user response:

The idea of using sets as your data-type is that you have a sure way to know that the values within this data-type are unique. Because the members of lists can change in the course of their lifetime, the set cannot be sure about its own promises of containing only distinct values.

From the Python Glossary "Hashable":
"Most of Python’s immutable built-in objects are hashable;
mutable containers (such as lists or dictionaries) are not;
immutable containers (such as tuples and frozensets)
are only hashable if their elements are hashable."

Python Glossary "Immutable"

Nice Stackoverflow Thread Explaining the Different Sequence-Types in Python

  • Related