# Set Data Type in Python

## Python Sets

Mathematically a set is a collection of elements, not having any particular order. A Python set is an unordered collection of immutable and unique elements. As the set elements are usually not stored in order of appearance in the set, so there is no index attached to any element. Thus they do not support any indexing or slicing operation.

### Creating Python sets

A Set is created by placing all the elements inside curly braces {} and separating them with a comma, or by using the built-in set() method.

Python seizes empty curly bracesĀ {} as an empty dictionary. Thus only set() method is used to define an empty set.

### Modifying a Python set

Elements of a set are immutable however, a set as a whole is mutable. Elements can be added and removed to a set in python.

### Frozenset

A frozen set in python is an immutable set. It has the same characteristics as of a normal set except that it cannot be changed once created. Frozensets are useful in situations where an immutable set is required. As sets are mutable they are unhashable, so they can’t be used as dictionary keys. On the other hand, frozensets are immutable thus they are hashable and can be used as keys to a dictionary.

The sets in python are typically used for removing duplicate values from a list or tuple and to perform mathematical operations like union, intersection, difference, etc.

### Set Operations

Python set is a mathematical notion of set. It is typically used for removing duplicate values from a list or tuple and performing mathematical operations like union, intersection, difference, etc.

#### Union

Union of set1 and set2 is a set of all elements from both sets. It is performed by using union() function or | operator.

### Intersection

Intersection of set1 and set2 is a set of elements that are common in both the sets. It is performed by using intersection() function or & operator.

#### Difference

Difference of the set1 from set2 is a set of elements that are only in set2 but not in set1. Similarly, difference of the set2 from set1 is a set of elements that are only in set1 but not in set2. It is performed by difference() method or – operator.

#### Symmetric Difference

Symmetric Difference of set1 and set2 is a set of elements in set1 and set2 but not in both. It is performed by using symmetric_difference() method or ^ operator