## Sets in Python

A set is an unordered collection of items. Each element is unique (no duplicates) and must be immutable (which cannot be changed). However, the set itself is mutable. We can add or remove items.

You can think of sets as a list. However, they differ in a list of the following ways:

If your application doesn't care how the items are stored, use sets rather than lists, because when it comes to handling items, a set is much more efficient than a list.

Sets can be used to perform operations of mathematical sets such as union, intersection, symmetric difference, etc.

#### Create a set

A set is created by placing all the elements (elements) between braces {}, separated by a comma or by using the integrated function **set().**

It can have any number of elements and they can be of different types (int, float, tuple, string, etc.). But a set cannot have a mutable item, like a list, a set, or a dictionary.

###### Example 1 :

# Create a set e1={1,3,5,7} print("type of e1 : ",type(e1)) print("Elements of e1 are : ",e1) e2={"Mostafa", 1.78, 32 } print("e2 : ",e2) # set with duplicates e3 = {3, 5, 7, 2, 3, 5} print("e5 : ", e5)

Elements of e1 are : {1, 3, 5, 7}

e2 : {32, 1.78, 'Mostafa'}

e3 : {2, 3, 5, 7}

We can also use the built-in set () function to create sets. Here are some examples:

###### Example 2 :

# create a set from another set e1 = set({77, 23, 91, 271}) print("e1 : ",e1) #create a set from a string e2 = set("123abc") print("e2 : ",e2) # create a set from a list e3 = set(['Mostafa', 'Sedoki', 'Meknes', 32, 1.78]) print("e3 : ",e3) #create a set from a tuple e4 = set(("Meknes", "Marrakech", "Essaouira")) print("e4 : ",e4)

e2 : {'3', 'b', '1', '2', 'a', 'c'}

e3 : {32, 1.78, 'Sedoki', 'Mostafa', 'Meknes'}

e4 : {'Marrakech', 'Essaouira', 'Meknes'}

#### Edit a set

The sets are mutable. But since they are not ordered, indexing does not make sense.

We cannot access or modify an item in a set using indexing or slicing. Set does not support it.

We can add a single element using the add() method and multiple elements using the update() method. The update() method can take tuples, lists, strings, or other sets as arguments. In all cases, duplicates are avoided.

###### Example 3 :

e={1,3} # add an element to the set e.add(5) print("e : ",e) # add multiple element from a list e.update([9,4,7]) print("e : ",e) # add a list and a set to the set e e.update([50,51],{100,200}) print("e : ",e)

e : {1, 3, 4, 5, 7, 9}

e : {1, 3, 4, 5, 100, 7, 200, 9, 50, 51}

#### Remove an item from a set

A particular item can be removed from the series using the methods, discard() and remove().

The only difference between the two is that, while using discard() if the element doesn't exist overall, it remains unchanged. But remove() throws an error in such a condition.

###### Example 4 :

e = {1, 3, 6, 7} e.discard(3) print("e : ", e) e.remove(7) print("e : ", e) e.discard(9) print("e : ", e) e.remove(9) print("e : ", e)

e : {1, 6}

e : {1, 6}

Traceback (most recent call last):

File "prog.py", line 12, in <module>

e.remove(9)

KeyError: 9

Likewise, we can delete and return an item using the pop() method.

Since sets are not ordered, there is no way to determine which item will be deleted. It is completely arbitrary. We can also remove all the elements of a set using clear().

###### Example 5 :

e={2, 4, 90, 100, 30, 32, 1} val=e.pop() print("val : ",val) print("e : ",e) e.clear() print("e : ",e)

e : {1, 2, 100, 4, 90, 30}

e : set()

#### Subset and Superset

The set B is a subset of A, if all the elements of the set B are also the elements of the set A. For example:

A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} B = {1, 2, 3}

A is a set of first 10 natural numbers and B is a set of first 3 natural numbers. All the elements of the set B are also the elements of the set B. Therefore, B is a subset of A. In other words, we can also say that the set A is a superset from B.

We can test whether a set is a subset or a superset of another set using the issubset() and issuperset() methods.

###### Example 6 :

A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} B = {1, 2, 3} # test if B is a subset of A if B.issubset(A): print("B is a subset of A") # test if A is superset of B if A.issuperset(B): print("A is a superset of B")

A is a superset of B

#### Compare sets

###### Example 7 :

A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} B = {1, 2, 3} if B < A): print("B is a subset of A") if A > B: print("A is superset of B") if A == B: print("A and B are same") if A>=B: print("A is superset or equal to B")

#### Union and intersection

#### Union

Suppose we have two sets A and B, the union of A and B is a set composed of all the elements of A and all the elements of B. Duplicate elements will be included only once. In mathematics, we use the symbol ∪ to denote the union. Symbolically, we write A union B as A ∪ B.

To perform a union operation in Python, we can use the union() or | operator. For example:

###### Example 8 :

A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} B = {1, 2, 3, 20, 34} C=A.union(B) print("Union : ", C)

#### Intersection

The intersection of sets A and B is a set made up of all the elements common to A and B. The symbol ∩ indicates the intersection. Symbolically, an intersection B is written A ∩ B.

To perform an intersection operation in Python, we use the intersection () method or the & operator. For example:

###### Example 9 :

A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} B = {1, 2, 3, 20, 34} C=A.intersection(B) print("Intersection : ", C)

#### Difference and symmetrical difference

#### Difference

The difference of the sets A and B is a set of elements which contains all the elements of the set A but not of B. As usual, we use the symbol - to indicate the operation of difference. Symbolically, A minus B is written A - B.

In Python, we use the difference() method or the operator - to make the defined difference.

###### Example 10 :

A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} B = {1, 2, 3, 20, 34} C=A.difference(B) print("A - B : ", C)

#### Symmetrical difference

The symmetrical difference of two sets A and B is a set made up of elements which are in a set but not in the two. The symbol △ indicates a symmetrical difference.

In Python, we use the symmetric_difference() method or the ^ operator to do this.

###### Example 11 :

A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} B = {1, 2, 3, 20, 34} C=A.symmetric_difference(B) print("Symmetrical difference : ", C)

#### Others sets methods

There are many methods, some of which have already been used previously. Here is a list of all the methods available with the objects together.

Method | Description |
---|---|

add() | Add an element to the set |

clear() | Remove all elements |

copy() | return a copy of the set |

difference() | Difference in two sets |

discard() | Remove an element from a set |

intersection() | Intersection of two sets |

isdisjoint() | return `True` if two sets have a zero intersection |

issubset() | Subset |

issuperset() | Superset |

pop() | Removes and returns an arbitrary element from the set. |

remove() | Remove an element from the set |

symmetric_difference() | Symmetrical difference of two sets |

union() | union of two sets |

update() | Update the set |

all() | return `True` if all the elements of the set are true (or if the set is empty). |

any() | return `True` if one element of the set is true. If the set is empty, return `False.` |

enumerate() | Returns an enumerated object. It contains the index and the value of all the elements of the set as a pair. |

len() | Set size |

max() | Maximum element of a set |

min() | Minimuym element of a set |

sorted() | Returns a new sorted list from the elements of the set (does not allow to sort the set itself) |

sum() | Sum of all items. |

#### Frozenset

Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. Tuples are immutable lists, frozensets are immutable sets.

The sets being mutable are unhashable, so they cannot be used as dictionary keys. 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 data type supports methods such as copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). Being immutable, there is no method to add or remove elements

###### Example 12 :

A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6])

#### Share this course with your friends :

**This course is written by M. ESSADDOUKI Mostafa**

## 0 Comment(s)