Set in Python

Set is an unordered collection of unique items . Since it is an unordered collection , hence there is no way to access individual item in a set. A set is written inside curly bracket same like dictionary but without any key.

Example:

x = {"apple", "banana", "cherry"}
print(x)

Output:

{'banana', 'apple', 'cherry'}

Since set is unordered so each time we will print the output the items will be printed in random fashion.

Set Membership:

To test whether an item is present in a set or not we will use “in” keyword.

Example:

x = {"apple", "banana", "cherry"}

if 'apple' in x :

print("Yes it is a member")

else:

print("Sorry")

Note: When checking for membership of a set, Python uses hash code (works same like keys in dictionary) so size of set has no effect on time taken to check if an item is present in it or not. Thus for large data , if we want to check membership set as a data type will be a lot faster and efficient than list.

Basic Set Operations:

Adding items to a set:

To add item to a pre-existing set use add function.

Example:

x= {"apple", "banana", "cherry"}

x.add("orange")

print(x)

Output:

{'apple', 'orange', 'banana', 'cherry'}

Let us look at one more example:

numbers={1,}

while len(numbers)<5:

next_value=int(input("Please enter your next value"))

numbers.add(next_value)

print(numbers)

Output:

Please enter your next value: 2
Please enter your next value: 2

Please enter your next value: 3

Please enter your next value: 4

{1,2,3,4}

Here in the above output though we were trying to add 2 , twice still the set will take it only once as it is a collection of unique items so any duplicate items would be discarded.

Deleting items from a set:

If we want to clear out all items in a list,dictionary or set then call the clear method.

Example:

fruits = {"apple", "banana", "cherry"}

fruits.clear()

print(fruits)

Output:

set()

While if we want to delete individual items use discard or remove method.

Difference between discard() and remove():

If suppose the item you want to delete is not present in the set then remove will raise an exception while discard won’t.

Example:

small_ints=set(range(21))

small_ints.discard(99)

print(small_ints)

Output:

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}

Here though 99 was not in set the discard method will not let the program crash and if suppose it was there then it would have removed it. But with remove method.

small_ints=set(range(21))

small_ints.remove(99)

print(small_ints)

Output:


Traceback (most recent call last):
 File "./prog.py", line 2, in <module>

KeyError: 99


Exception would be raised if item is not in set.

What about pop method ?

Since items in a set are not indexed , hence pop method , pops an arbitrary item from set and return that item.

Example:

fruits = {"apple", "banana", "cherry"}

x = fruits.pop()

print(x)

Output:

banana

Various set operations:

Set Union:

Union of two or more set is the set of element from all sets.

Syntax is : set1.union(*others) where set1 is the first set and others is n number of set or any iterable you want to call union operation on.

Example:

farm_animals={"sheep","hen","cow","horse","goat"}

wild_animals={"lion","elephant","tiger","goat","panther","horse"}

all_animals=farm_animals.union(wild_animals)

print(all_animals)

Output:

{'hen', 'cow', 'lion', 'tiger', 'elephant', 'panther', 'sheep', 'horse', 'goat'}

Note: Set Union is Commutative

Set Update:

It updates the existing set rather than creating a new one with the value we want to insert.

Example:

set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}

set1.update(set2)

print(set1)

Output:

{'banana', 'google', 'microsoft', 'apple', 'cherry'}

Set Intersection:

It produces a new set containing only those elements that are in both the set i.e common one.

Syntax is : set1.intersection(*others) where set1 is the first set and others is n number of set or any iterable you want to call intersection operation on.

farm_animals={"sheep","hen","cow","horse","goat"}

wild_animals={"lion","elephant","tiger","goat","panther","horse"}

potential_rides={"donkey","horse","camel"}

mounts=farm_animals.intersection(wild_animals,potential_rides)

print(mounts)

Output:

{'horse'}

Set Difference:

It is the set of all those items that are in one set but not in the other

Example:

set1= {"apple", "banana", "cherry"}

set2 = {"google", "microsoft", "apple"}

final_set = set1.difference(set2)

print(final_set)

Output:

{'banana','cherry'}

Note: Set difference is non-commutative

If we want to remove anything that exist in a set than rather iterating over the set using discard method we can go for set difference.

Symmetric Difference:

It is simply the opposite of intersection. It basically produces the set of items that are in one set or other but not in both.

Example:

farm_animals={"sheep","hen","cow","horse","goat"}

wild_animals={"lion","elephant","tiger","goat","panther","horse"}

mounts=farm_animals.symmetric_difference(wild_animals)

print(mounts)

Output:

{'lion', 'sheep', 'tiger', 'elephant', 'panther', 'hen', 'cow'}

Note:Symmetric difference is commutative and it takes only 1 argument.

Leave a Reply

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