**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?**

Table of Contents

## 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)

- O(1) means in constant time – independent of the number of items.
- O(N) means in proportion to the number of items.
- 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/Method | Example | Complexity |
---|---|---|

Length | len(s) | O(1) |

Add | s.add(s) | O(1) |

Containment | x in/not in s | O(1) |

Remove | s.remove(….) | O(1) |

Discard | s.discard(….) | O(1) |

Pop | s.pop() | O(1) |

Clear | s.clear() | O(1) |

Construction | set(…..) | O(len(…..)) |

check ==, != | s != v | O(len(s)) |

Is Subset | set1 <= set2 | O(len(set1)) |

Is Superset | set1 >= set2 | O(len(set2)) |

Union | set1 | set2 | O(len(set1) + len(set2)) |

Intersection | set1 & set2 | O(len(set1) + len(set2)) |

Difference | set1 – set2 | O(len(set1) + len(set2)) |

Symmetric Difference | set1 ^ set2 | O(len(set1) + len(set2)) |

Iteration | for v in s: | O(N) |

Copy | s.copy() | O(N) |

## No Comments

Leave a comment Cancel