Python Tutorial

Python - Introduction
Python - Syntax
Python - Variable
Python - Number
Python - Casting
Python - String
Python - Operators
Python - Conditions
Python - Loops
Python - List
Python - Tuple
Python OOP

OOP - Introduction
OOP - Class Members
OOP - Constructor Destructor
OOP - Data Hiding
OOP - Inheritance
OOP - Overriding
OOP - Overloading
A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements.

Python's set class represents the mathematical notion of a set. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a **hash table**.

A set is a collection which is **unordered** and **unindexed**. In Python sets are written with curly brackets.

In a set we can't have duplicate items.

In Python sets are written with curly brackets.

`set1 = {1, 2, 3, 4, 5, 1, 1}`

`set2 = {'apple', 'mango', 'cherry'}`

`set3 = {'apple', 'mango', 7, 'cherry', 2, 3}`

As set is unindexed we can't use `[]`

to access elements of a set.

But we can use for loop to access set elements:

`set1 = {'apple', 'mango', 'cherry'}`

`for x in set1:`

`print(x)`

You can add to elements in a set with the `add()`

method:

`set1 = {1, 2, 3, 4, 5, 1, 1}`

`set1.add(500)`

`set1.add(25)`

Set elements can be removed using `pop()`

and `remove()`

methods:

`pop()`

method delete element from begining of set`remove()`

method takes an argument and delete that element from set

`set1 = {1, 2, 3, 4, 5}`

``

`set1.pop()`

`print(set1) # print {2, 3, 4, 5}`

``

`set1.remove(4)`

`print(set1) # print {2, 3, 5}`

Function | Description |
---|---|

`len(` |
Gives the total length of the set (duplicate values excluded). |

`max(` |
Returns item from the set with max value. |

`min(` |
Returns item from the set with min value. |

`set(` |
Converts a tuple or list into set. |

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

`set.add(x)` |
Adds the item x to set if it is not already present in the set |

`set.clear()` |
Empties the whole set |

`set.copy(o)` |
Copy a set to another set |

`set.union(s)` |
Returns a union of two set. Using the `|` operator between 2 sets is the same as writing set1.union(set2) |

`set.intersection(s)` |
Returns intersections/common of two sets.The `&` operator comes can also be used in this case. |

`set.difference(s)` |
Returns a set containing all the elements of invoking set but not of the second set |

`set.pop()` |
Remove element from begining |

`set.remove(elem)` |
Remove elem from set |