Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Does the set.add() function not add duplicates?

Tags:

python

set

I have multiple tuples stored in a set, and I'm trying to add two duplicate tuples to the set through a nested for loop which basically iterates through another bunch of tuples and checks for a condition in the tuple, then adds the tuple to the set if the tuple meets the condition. However, some tuples are duplicate and I'm noticing the duplicates aren't being added.

like image 615
SKLAK Avatar asked Feb 15 '13 01:02

SKLAK


People also ask

Does set Add duplicates?

A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

What does set () do in Python?

set() method is used to convert any of the iterable to sequence of iterable elements with distinct elements, commonly called Set. Parameters : Any iterable sequence like list, tuple or dictionary. Returns : An empty set if no element is passed.

How do you prevent duplicates in Python?

If you don't want duplicate elements, you should use Set. But, if you have to remove the duplicate values from a list, then I would prefer count() function because it doesn't create another temporary set or list object. So, it's more memory efficient.


2 Answers

Set by definition is unordered collections of unique elements, so they don't allow duplicates. Please check the python's documentation.

like image 96
Hui Zheng Avatar answered Sep 19 '22 06:09

Hui Zheng


A set can not contain duplicates. That is the point of a set. If you want duplicates, consider using a list instead.

like image 44
Josh Smeaton Avatar answered Sep 22 '22 06:09

Josh Smeaton