How do sets work in Python

0 votes
I have a list of objects which I want to turn into a set. My objects contain a few fields that some of which are o.id and o.area. I want two objects to be equal if these two fields are the same. ie: o1==o2 if and only if o1.area==o2.area and o1.id==o2.id.

I tried over-writing __eq__ and __cmp__ but I get the following error:

TypeError: unhashable instance.

Please tell me what should I over-write?
Apr 12, 2019 in Python by ana1504.k
• 7,910 points
576 views

1 answer to this question.

0 votes
Define the __hash__ method to return a meaningful hash based on the id and area fields.

For example, you can try this:

def __hash__(self):
    return hash(self.id) ^ hash(self.area)
answered Apr 12, 2019 by SDeb
• 13,300 points

Related Questions In Python

0 votes
2 answers

How do I copy a file in python?

copy a file in python  from shutil ...READ MORE

answered Mar 27, 2019 in Python by rajesh
• 1,270 points
971 views
0 votes
1 answer

How do you get the logical xor of two variables in Python?

If you're already normalizing the inputs to ...READ MORE

answered May 29, 2018 in Python by aryya
• 7,450 points
10,468 views
0 votes
1 answer

How do I copy a file in python?

Use the shutil module. copyfile(src, dst) Copy the contents ...READ MORE

answered Jul 31, 2018 in Python by Priyaj
• 58,090 points
742 views
0 votes
1 answer

How do you get the logical xor of two variables in Python?

What i found is that you can use ...READ MORE

answered Aug 10, 2018 in Python by Priyaj
• 58,090 points
11,334 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,070 views
0 votes
1 answer
0 votes
2 answers

In Python, how do I read a file line-by-line into a list?

readline function help to  read line in ...READ MORE

answered Jun 21, 2020 in Python by sahil
• 580 points
1,476 views
0 votes
1 answer

How does % work in Python?

The % (modulo) operator yields the remainder ...READ MORE

answered Oct 10, 2018 in Python by SDeb
• 13,300 points
626 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP