Understand Python sets

Understand Python sets

◽️ A set is a collection which is both unordered and unindexed. ◽️ Once created, you cannot change its items, but you can add new items. ◽️ 2 items cannot have same value. ◽️ Items can be of any data type.

How to create sets ?

◽️ Using the set() constructor: myset = set(("apple", "banana"))

◽️ Directly using Curly braces: myset = {"apple", "banana"}

Let's dive into set methods 👇

1⃣ add() method adds an element to the set.

set.add(elmnt)

2⃣ clear() method removes all elements in a set.

set.clear()

3⃣ difference() method returns a set that contains the difference between two sets.

set.difference(set)

It returns items that exist only in the first set, and not in both sets

4⃣ discard() method removes the specified item from the set.

set.discard(value)

In set, remove() method raises an error if the specified item does not exist, and the discard() method doesn't.

5⃣ intersection() method returns a set that contains the similarity between two or more sets.

set.intersection(set1, set2 ... etc)

6⃣ issubset() method returns True if all items in the set exists in the specified set, otherwise it returns False.

set.issubset(set)

7⃣ pop() method removes a random item from the set

set.pop()

8⃣ union() method returns a set that contains all items from the original set, and all items from the specified sets.

set.union(set1, set2...)

9⃣ update() method updates the current set, by adding items from another set.

set.update(set)

If you found this post on Python sets helpful, then don't forget to ♥️ it.

Don't forget to follow for more Machine Learning and Python related contents.

More contents coming 😃