Python Sets Operations/Methods Time Complexity

Sets are unordered collection of items in Python, it doesn’t contain duplicate objects and also objects contained by a set need to be immutable. But Set itself is mutable. Because Sets are mutable meaning these can be changed there exist many methods for doing this, if your not aware of those methods/operations then see What are Set Methods/Operations in Python? article in which I’ve listed all of Python’s Set Methods.

Let’s first talk about What’s Time Complexity in Programming and Why you as a Python Developer need to care about this?

What is Complexity in Programming?

Complexity or O(n) is measurement of How many items needed to be considered for execute something. From daily life you can think this of as brushing your teeth, How many steps items you need to do brushing can be consider Complexity.(Quite Simple!!)

Why Programmer need to consider Complexity? Complexity needs to be considered by programmer while writing code as sometimes a piece of code need to be executed fast or sometime slower. For example – If your writing code for a Self Driving Car then you want code to be executed faster so that action(Turning Left/Right) can be taken quickly.

Defining Complexity Mathematically O(n)

  1. O(1) means in constant time – independent of the number of items.
  2. O(N) means in proportion to the number of items.
  3. O(log N) means a time proportional to log(N)

Basically any ‘O’ notation means an operation will take time up to a maximum of k*f(N)
where: k is a constant multiplier and f() is a function that depends on N

Table containing Sets Operations/Methods Complexity in Python

Just note that s, set1, set2 are Python Sets and v is any Data value in table below.

Set Operation/MethodExampleComplexity
Lengthlen(s)O(1)
Adds.add(s)O(1)
Containmentx in/not in sO(1)
Removes.remove(….)O(1)
Discards.discard(….)O(1)
Pops.pop()O(1)
Clears.clear()O(1)
Constructionset(…..)O(len(…..))
check ==, !=s != vO(len(s))
Is Subsetset1 <= set2O(len(set1))
Is Supersetset1 >= set2O(len(set2))
Unionset1 | set2O(len(set1) + len(set2))
Intersectionset1 & set2O(len(set1) + len(set2))
Differenceset1 – set2O(len(set1) + len(set2))
Symmetric Differenceset1 ^ set2O(len(set1) + len(set2))
Iterationfor v in s:O(N)
Copys.copy()O(N)

You May Also Like

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts