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:

    l1=set(map(int, input().split()))
    n=int(input())
    l2=set()
    for i in range(n):
        l2.add([int, input().split()])
    print(l1)
    print(l2)

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 :

l2=set()
for i in range(n):
    l2.add(map(int, input().split()))

The above prints out :

{<map object at 0x000001D5E88F36A0>, <map object at 0x000001D5E8C74AC8>}

Even this does not work!!

for i in range(n):
    l2.add(set(map(int, input().split())))

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:

1 2 3 4 5 6 7 8 9 10 11 12 23 45 84 78
2
1 2 3 4 5
100 11 12

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:

{{1,2,3,4,5},{100,11,12}}

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:

l2 = set()
for i in range(n):
    l2.add(frozenset(map(int, input().split())))

OR

l2 = {frozenset(map(int, input().split())) for i in range(n)}

OR

l2 = set(frozenset(map(int, input().split())) for i in range(n))

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