Python Sets and Frozensets

aimtocode

Python Set Definition

A set is an unordered collection data type with no duplicate elements. Sets are iterable and mutable. The elements appear in an arbitrary order when sets are iterated.

The elements of the set can not be duplicate. The elements of the python set must be immutable.

Unlike arrays, where the elements are stored as ordered list, the order of elements in a set is undefined (moreover, the set elements are usually not stored in order of appearance in the set; this allows checking if an element belongs to a set faster than just going through all the elements of the set).


Creating a Set

Sets can be created by calling the built-in set() function with a sequence or another iterable object.

A set can be created also by using the curly braces as well.


Example 1: using set() method



Output:

 Printing the element using for loop...
 Pankaj
 Sujeet
 Rahul
 Amol
 Prayag
 Rakesh
 Mukesh

Example 2: using curly praces




Output:

 Printing the element using for loop...
 Sujeet
 Rakesh
 Mukesh
 Amol
 Rahul
 Prayag
 Pankaj


Python Set operations

Python sets can be used to perform some mathematical set operations like union, intersection, difference and symmetric difference. We can do this with operators or methods.


Add Items

If we want to add single item to a list, we can use add() method.

If we want to add more than one item to a list, we can use update() method.


Example: using Add() method




Output:

 Printing the element using for loop...
 Anmol
 Rakesh
 Prayag
 Sujeet
 Rahul
 Aimtocode
 Mukesh
 Pankaj

Here, in above example by using add() method and adding one element Aimtocode.


Example : using update() method



Output:

 Printing the element using for loop...
 Sujeet
 tutorial
 Rahul
 Python
 Mukesh
 Prayag
 Anmol
 Aimtocode
 Pankaj
 Rakesh

In above example, update() method is used to add multiple elements.


Removing elements from a set

There are a number of ways to remove items from a set:

  • Use the remove() method if you want to remove a single element from a set, or get an error message if the respective item is not in the set.
  • Use the discard() method if you want to remove a single element from a set but don’t need an error message if the given item is not in the set.
  • Use the pop() method to remove and return a random element from a set.
  • Use the clear() method to remove all items from a set.

Example:



Output:

 Printing the element using for loop...
 Rakesh
 Pankaj
 Anmol
 Mukesh
 Sujeet
 Rahul

In above example, remove() method is used to remove the element Prayag.


Example: using discard() method




Outpu:

 Printing the element using for loop...
 Rahul
 Anmol
 Prayag
 Mukesh
 Pankaj
 Sujeet

In above example, discard() method is used to discard the element Rakesh.


Example: pop() method




Outpu:

 Rahul
 {'Aimtocode', 'Anmol', 'Prayag'}

You can also use the pop(), method to remove an item, but this method will remove the last item.



Union of two Sets

If there are two sets, first_set and second_set, the union of these two sets is the set of all elements from both sets.

The union of two sets are calculated by using the or (|).


Example : using union | operator




Output:

 {'Rahul', 'Prayag', 'Anmol', 'Aimtocode'}


Example : using union() method




Output:

 {'Prayag', 'Aimtocode', 'Anmol', 'Rahul'}


Set intersection_update() method

The intersection of two sets, first_set and second_set, is the set of all elements common to both sets.

This operation can be performed using the & operator or the intersection() method.




Output:

 {4, 5}

As you can see, both the intersection() method and the & operator allow you to create an intersection for more than two sets.



Python FrozenSets

The frozen set is just an unchangeable category of a Python set object.

On the other hand, frozensets are hashable and can be used as keys to a dictionary.

Frozensets can be created using the function frozenset().

This datatype supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union().

Since frozenSets is immutable it does not have method that add or remove elements.

The frozenset() function returns an unchangeable frozenset object (it is like a set object, only unchangeable).


Syntax:

 
 frozenset(iterable) 


Example 1: FrozenSets



Output:

 frozenset({'Prayag', 'Aimtocode', 'Anmol', 'Rahul'})	


Example 2:


This will cause an error Type:

Output:

 Traceback (most recent call last):
  File "C:\Python\frozen.py", line 3, in 
    a[1] = "Python"
 TypeError: 'frozenset' object does not support item assignment


Python Set Built-in Methods

There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with set objects.


Method Description
add()Adds an element to the set
clear()Removes all the elements from the set
copy()Returns a copy of the set
difference()Returns a set containing the difference between two or more sets
difference_update()Removes the items in this set that are also included in another, specified set
discard()Remove the specified item
intersection()Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other, specified set(s)
isdisjoint()Returns whether two sets have a intersection or not
issubset()Returns whether another set contains this set or not
issuperset()Returns whether this set contains another set or not
pop()Removes an element from the set
remove()Removes the specified element
symmetric_difference()Returns a set with the symmetric differences of two sets
symmetric_difference
_update()
inserts the symmetric differences from this set and another
union()Return a set containing the union of sets
update()Update the set with the union of this set and others



Set Built-in Functions

Function Description
all() Return True if all elements of the set are true (or if the set is empty).
any() Return True if any element of the set is true. If the set is empty, return False.
enumerate() Return an enumerate object. It contains the index and value of all the items of set as a pair.
len() Return the length (the number of items) in the set.
max() Return the largest item in the set.
min() Return the smallest item in the set.
sorted() Return a new sorted list from elements in the set(does not sort the set itself).
sum() Retrun the sum of all elements in the set.
aimtocode