A set is a collection of unique data. That is, elements of a set cannot be duplicated. For example,

Suppose we want to store information about**student ID cards**. Since**student ID cards**cannot be duplicated, we can use a set.

## Create a sentence in Python

In Python, we create sets by placing all elements in curly braces`{}`

, separated by commas.

A set can have any number of elements and they can be of different types (integer, float, tuple, string, etc.). But a set cannot have mutable elements likeListen, sentences ordictionariesas its elements.

Let's look at an example

`# Make a series of integers typestudent_id = {112, 114, 116, 118, 115}print('Student ID:', student_id)# Make a series of strings typevowel_letters = {'a', 'e', 'i', 'o', 'u'}print('Vowel Letters:', vowel_letters)# create a mixed datatype setmixed_set = {'Hello', 101, -2, 'Bye'}print('Mixed datatype set: ', mixed sentence)`

**Exit**

Student ID: {112, 114, 115, 116, 118}Vocal Letters: {'u', 'a', 'e', 'i', 'o'}Mixed Data Type Set: {'hello', ' Goodbye', 101, -2}

In the example above, we created different types of sets by placing all the elements inside the curly brackets`{}`

.

**Note:**If you run this code, you may get output in a different order. This is because the set is in no particular order.

## Create an empty set in Python

Creating an empty set is a bit tricky. Empty braces`{}`

will make a blankdictionaryin Python.

To create a set with no elements, we use theSentence()Function with no argument. For example,

`# create an empty setempty_set = set()# create an empty dictionaryempty_dictionary = { }# check the data type of empty_setprint('data type of empty_set:', type(empty_set))# check the data type of dictionary_setprint('data type of empty_dictionary' , type (empty_dictionary))`

**Exit**

Data type of empty_set: <class 'set'>Data type of empty_dictionary <class 'dict'>

Here,

`empty set`- an empty set created with`Sentence()`

`empty_dictionary`- an empty dictionary created with`{}`

Finally we used it`Typ()`

Function to know which class`empty set`And`empty_dictionary`belong.

## Duplicate items in one set

Let's see what happens when we try to include duplicate elements in a sentence.

`numbers = {2, 4, 6, 6, 2, 8}print(numbers) # {8, 2, 4, 6}`

Here we can see that the set does not contain any duplicate elements, since a set cannot contain any duplicates.

## Adding and updating set items in Python

Quantities are variable. However, since they are unordered, the indexing has no meaning.

We cannot access or modify an element of a set using indexing or slicing. Set data type does not support it.

### Adding elements to a set in Python

In Python we use the`add to()`

Method for adding an element to a set. For example,

`Zahlen = {21, 34, 54, 12}print('Initial Set:',Zahlen)# using add() methodnumbers.add(32)print('Updated Set:', Numbers)`

**Exit**

First set: {34, 12, 21, 54} Updated set: {32, 34, 12, 21, 54}

In the example above, we created a set named`Pay`. notice the line

`numbers.add(32)`

Here,`add to()`

adds**32**to our sentence.

### Update Python set

The`To update()`

method is used to update the set with elements of other collection types (lists, tuples, sets, etc.). For example,

`Companies = {'Lacoste', 'Ralph Lauren'}tech_companies = ['apple', 'google', 'apple']companies.update(tech_companies)print(companies)# Output: {'google', 'apple', ' Lacoste', 'Ralph Lauren'}`

Here are all the unique elements of`tech_company`

are added`companies`

Sentence.

## Remove an element from a set

We use that`discard()`

method to remove the specified element from a set. For example,

`languages = {'Swift', 'Java', 'Python'}print('Initial Set:',languages)# remove 'Java' from a SetremovedValue = languages.discard('Java')print('Set after remove () :', Languages)`

**Exit**

Initial Set: {'Python', 'Swift', 'Java'}Set after remove(): {'Python', 'Swift'}

Here we used that`discard()`

remove method`'Java'`

of the`Languages`Sentence.

## Built-in functions with set

Built-in functions like`at()`

,`any()`

,`enumerate()`

,`len()`

,`max()`

,`Minimum()`

,`sorted ()`

,`Total()`

etc. are commonly used with sentences to perform various tasks.

function | Description |
---|---|

at() | Returns`TRUE` if all elements of the set are true (or if the set is empty). |

any() | Returns`TRUE` if any member of the set is true. If the lot is empty, will be returned`INCORRECT` . |

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

len() | Returns the length (the number of elements) in the set. |

max() | Returns the largest element in the set. |

Minimum() | Returns the smallest element in the set. |

sorted () | Returns a new sorted list of elements in the set (does not sort the set itself). |

Total() | Returns the sum of all elements in the set. |

## Iterate over a crowd in Python

`fruits = {"apple", "peach", "mango"}# For loop to access each fruit for fruits in fruits: print(fruit)`

**Exit**

MangoPfirsichApfel

## Find the number of set elements

We can use those`len()`

Method to get the number of elements present in a set. For example,

`even_numbers = {2,4,6,8}print('Set:',even_numbers)# Find number of elements print('Total Elements:', len(even_numbers))`

**Exit**

Theorem: {8, 2, 4, 6} Total elements: 4

Here we used that`len()`

Method to get the number of elements present in a set.

## The Python Set Operation

Python Set provides several built-in methods for performing mathematical set operations such as union, intersection, subtraction, and symmetric difference.

### Union of two sets

The union of two sets**A**And**B**contain all elements of set**A**And**B**.

We use that`|`

operator or the`Union()`

-Method to perform set union operation. For example,

`# first setA = {1, 3, 5}# second setB = {0, 2, 4}# union operation with |print('Union using |:', A | B)# union operation with union()print perform ('Union using union():', A.union(B))`

**Exit**

Union with |: {0, 1, 2, 3, 4, 5} Union with union(): {0, 1, 2, 3, 4, 5}

**note**:`A|B`

And`Union()`

is equivalent to`A⋃B`

stop operation.

### set intersection

The intersection of two sets**A**And**B**contain the common elements between set**A**And**B**.

In Python we use the`&`

operator or the`Overlap()`

-Method to perform set cutting operation. For example,

`# first setA = {1, 3, 5}# second setB = {1, 2, 3}# intersection operation with &print('intersection with &:', A & B)# intersection operation with intersection()print( 'intersection with intersection ():', A.Intersection(B))`

**Exit**

Intersection with &: {1, 3}Intersection with intersection(): {1, 3}

**note**:`A&B`

And`Overlap()`

is equivalent to`A⋂B`

stop operation.

### difference between two sentences

The difference between two sentences**A**And**B**Contain elements of set**A**that are not present on the set**B**.

We use that`-`

operator or the`Difference()`

Method to run the difference between two sentences. For example,

`# first setA = {2, 3, 5}# second setB = {1, 2, 6}# difference operation with &print('difference with &:', A - B)# difference operation with difference()print( 'difference with difference ():', A.difference(B))`

**Exit**

Difference with &: {3, 5} Difference with Difference(): {3, 5}

**note**:`A-B`

And`A. Difference (B)`

is equivalent to`A-B`

stop operation.

### Set symmetrical difference

The symmetric difference between two sets**A**And**B**contains all elements of**A**And**B**without the common elements.

In Python we use the`^`

operator or the`Symmetric_difference()`

Method for performing a symmetrical difference between two sentences. For example,

`# first setA = {2, 3, 5}# second setB = {1, 2, 6}# difference operation with &print('using ^:', A ^ B)# with symmetric_difference()print('using symmetric_difference( ): ', A.symmetric_difference(B))`

**Exit**

mit ^: {1, 3, 5, 6} mit symmetric_difference(): {1, 3, 5, 6}

## Check if two sentences are equal

We can use those`==`

Operator to check if two sets are equal or not. For example,

`# first setA = {1, 3, 5}# second setB = {3, 5, 1}# perform difference operation with &if A == B: print('set A and set B are equal')else: print(' set A and sentence B are not the same')`

**Exit**

Set A and Set B are the same

In the example above`A`And`B`have the same elements, i.e. the condition

`if A == B`

evaluates`TRUE`

. Hence the statement`print('Set A and Set B are the same')`

within the`If`

is running.

## Other Python Set Methods

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

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

add to() | Adds an item to the set |

clear() | Removes all items 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 item from the set if it is a member. (Do nothing if item is not in set) |

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

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

is disjoint () | Returns`TRUE` if two sets have a zero intersection |

issubset() | Returns`TRUE` if another sentence contains this sentence |

superset() | Returns`TRUE` if this sentence contains another sentence |

Pop() | Removes and returns any set item. Elevated`key error` when the crowd is empty |

removed() | Removes an item from the set. If the element is not a member, a is thrown`key error` |

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 into a new set |

To update() | Updates the crowd with the union of self and others |