DEV Community

Cover image for Settling with Sets 2.0 - Python
Sakshi
Sakshi

Posted on

Settling with Sets 2.0 - Python

Python Unleash'd 11

Consider reading this first

1. Access elements

You can not access elements using index, so the only way is to loop through the elements, takes O(n) time.

2. Removing Elements

We have a 'remove' method to serve this purpose. It throws error if element is not in the set. To use remove(), first check if element is present. It take O(n) time to check element's presense.

Better to use 'discard()', as it does not throw any error even if element is not present.

Image description

3. Pop

Pop() function can also be used to remove and return an element from the set, but it removes only the last element of the set.

As set is unordered there is no way to tell which element is removed. :D

Image description

4. clear()

To remove all elements from set, use clear() method.

Image description

DO YOU KNOW

  1. There is something 'frozenset' which makes a set immutable and then only those methods are applied which does not affect elements

  2. All mathematical operations are valid on these sets : union, intersection, difference, issubset, issuperset etc

  3. It does not support append()

  4. Consumer more memory than lists

THANKS FOR READING GUYS

keep reading :)

Image description

Top comments (0)