# Python Set

### Python set is an unordered collection of items which are unique within that set. The order in which item in sets is placed is undefined. Sets are enclosed in brackets {} with items comma separated. Set is a mutable data type, so we can add or remove items from a set.

Contents

- 1 How to create a set in Python?
- 2 How to change or add elements to a set in Python?
- 3 How to delete or remove elements from a set in Python?
- 4 How to iterate over a Set in Python?
- 5 What is Python Frozenset?
- 6 What are Python Set Operations?
- 7 What are Python Set Built-in functions?
- 8 What are Python Set built-in methods?

## How to create a set in Python?

Set in Python is created using curly brackets {} with the items in the set be separated by a comma (,). A set can have any number of items and can be of different data types. To have an idea of python data types, please refer to this tutorial:- Python Datatypes.

Let’s explore some of the examples of the set in the following example:-

1 2 3 4 5 6 7 8 9 | a = {5, 2, 3, 1, 4} days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"} # printing set variable print("a = ", a) print(days) # data type of variable a print(type(a)) |

The output of the above program is:-

{‘Wednesday’, ‘Friday’, ‘Thursday’, ‘Tuesday’, ‘Saturday’, ‘Monday’, ‘Sunday’}

<class ‘set’>

## How to change or add elements to a set in Python?

Since sets are mutable data types, you can add, edit or delete every item in a set. As a set is not indexable in Python, we cannot access any particular index of the item, so we need a function to add an item to set. We can add a single item using add() method and multiple using update() method in the set.

1 2 3 4 5 6 | days = {"Sunday", "Monday"} print("Current set", days) days.add("Tuesday") print("New set", days) days.update({"Wednesday", "Thursday", "Friday"}) print("New set", days) |

New set {‘Monday’, ‘Sunday’, ‘Tuesday’}

New set {‘Thursday’, ‘Friday’, ‘Tuesday’, ‘Wednesday’, ‘Monday’, ‘Sunday’}

## How to delete or remove elements from a set in Python?

We can use discard() or remove() function to remove the item from a set. discard() function doesn’t throw error if the item is not found, whereas remove() function throws an error if the item is not found.

1 2 3 4 | days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} print("Current set", days) days.discard("Sunday") print("Updated set", days) |

Updated set {‘Saturday’, ‘Friday’, ‘Tuesday’, ‘Wednesday’, ‘Monday’, ‘Thursday’}

## How to iterate over a Set in Python?

A set can be iterated using for loop. Let us see the following example:-

1 2 3 | days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} for day in days: print(day) |

Saturday

Monday

Sunday

Wednesday

Thursday

Friday

## What is Python Frozenset?

Frozenset is an immutable set where set once defined cannot be changed. Sets are unhashable, so they can’t be used as dictionary keys. Frozensets are hashable and can be used as keys to a dictionary. This datatype supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). There are no methods as add or remove elements in a set. We can initialize frozen set as below:-

1 2 3 | # initialize A and B A = frozenset([1, 2, 3, 4]) B = frozenset([3, 4, 5, 6]) |

## What are Python Set Operations?

Operator | Description |

A | B A.union(B) | Returns a set which is the union of sets A and B. |

A |= B A.update(B) | Adds all elements of array B to the set A. |

A & B A.intersection(B) | Returns a set which is the intersection of sets A and B. |

A &= B A.intersection_update(B) | Leaves in the set A only items that belong to the set B. |

A – B A.difference(B) | Returns the set difference of A and B (the elements included in A, but not included in B). |

A -= B A.difference_update(B) | Removes all elements of B from the set A. |

A ^ B A.symmetric_difference(B) | Returns the symmetric difference of sets A and B (the elements belonging to either A or B, but not to both sets simultaneously). |

A ^= B A.symmetric_difference_update(B) | Writes in A the symmetric difference of sets A and B. |

A <= B A.issubset(B) | Returns true if A is a subset of B. |

A >= B A.issuperset(B) | Returns true if B is a subset of A. |

A >= B A.issuperset(B) | Returns true if B is a subset of A. |

A < B | Equivalent to A <= B and A != B |

A > B | Equivalent to A >= B and A != B |

Let’s use some examples to get an idea on set operations:-

1 2 3 4 5 6 7 8 9 | A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A | B) #Set Union print(A & B) #Set Intersection #Alternate way print(A.union(B)) print(A.intersection(B)) |

{4, 5}

{1, 2, 3, 4, 5, 6, 7, 8}

{4, 5}

## What are Python Set Built-in functions?

Python provides the following built-in functions which can be used with the sets.

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 enumerated object. It contains the index and value of all the items of a 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() | Return the sum of all elements in the set. |

## What are Python Set built-in methods?

Python provides various methods that can help you perform the various operations in a set. Following are some of the built-in sets methods:-

Method | Description |

add() | Adds an element to the set |

clear() | Removes all elements from the set |

copy() | Returns a copy of the set |

difference() | Returns the difference of two or more sets as a new set |

difference_update() | Removes all elements of another set from this set |

discard() | Removes an element from the set if it is a member. (Do nothing if the element is not in set) |

intersection() | Returns the intersection of two sets as a new set |

intersection_update() | Updates the set with the intersection of itself and another |

isdisjoint() | Returns True if two sets have a null intersection |

issubset() | Returns True if another set contains this set |

issuperset() | Returns True if this set contains another set |

pop() | Removes and returns an arbitrary set element. Raise KeyError if the set is empty |

remove() | Removes an element from the set. If the element is not a member, raise a KeyError |

symmetric_difference() | Returns the symmetric difference of two sets as a new set |

symmetric_difference_update() | Updates a set with the symmetric difference of itself and another |

union() | Returns the union of sets in a new set |

update() | Updates the set with the union of itself and others |

## Recent Comments