Skip to content
Advertisement

How to add() runtime input in a set in python?

Problem

I am trying to add() elements in a set at run time using a for loop:

JavaScript

Surprisingly, l1 is a set but, when I go on add() -ing elements to my set l2 in a loop I get :

TypeError: unhashable type: ‘list’

Research Effort:

Here are other ways I have tried to add() elements to set l2 and failed :

JavaScript

The above prints out :

JavaScript

Even this does not work!!

JavaScript

Please feel free to point out what I am doing wrong.

Basically, an answer will be helpful if one can explain how to add elements to a set data structure at runtime in a loop

Clarification:

I am looking for making a set of sets with user inputs at run time:

So if the user gives the following input:

JavaScript

The first line is my set l1. The second line is the number of sets and so since it is 2, the line afterwards are contents of the set.

Expected output:

JavaScript

Advertisement

Answer

Since l am now answering an essentially different question, I am posting a second answer.

A set is mutable, and therefore unhashable. Mutable objects can implement a hash function, but the built-in ones generally don’t to avoid issues. Instead of using a set, use a hashable frozenset for your nested sets:

JavaScript

OR

JavaScript

OR

JavaScript

You won’t be able to modify the sub-sets of l2, but they will behave as sets for at other purposes.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement