# Python Sets – The collection of unordered and unindexed Python objects

Till now, we saw various data types in Python which include numbers, strings, lists, tuples, and dictionaries. Today, we are going to see another data type that is Python Sets. We will see what sets are and how you can create, access and perform operations on them. We will also see the functions associated with them. So let’s start with the concept of Python sets.

## Python Sets

Sets in Python are a collection of unordered and unindexed Python objects. Sets are mutable, iterable and they do not contain duplicate values. It is similar to the concept of the mathematical set.

### Create a Set in Python

The elements in a set are declared inside curly braces separated by commas.

**Code:**

#sets are unordered, it rearranges itself in sorted order a = {1, 2, 7, 5, 5} b = {99, 100, 200, “yes”, “no”} #empty set are created using the set() function empty_set = set() print(empty_set) print(type(empty_set)) empty_dictionary = {} print(type(empty_dictionary))

**Output:**

<class ‘set’ >

<class ‘dict’ >

### Accessing Python Sets

As we discussed earlier that sets in Python are unindexed, so we access the entire set at once in sorted order.

**Code:**

a = {7, 6, 5, 4, 3, 4, 5, 6} print(a)

**Output:**

See how the elements are sorted and duplicates are reduced in sets.

Since the sets are unindexed, we cannot use slicing or indexing on sets, it will give us a TypeError error when using indexing.

**Code:**

a = {1,2,3,4} print(a[2])

**Output:**

**File “<stdin>”, line 2, in <module>**

TypeError: ‘set’ object does not support indexing

### Iterating on Sets in Python

Sets are iterable and we can iterate over them with a ‘for’ loop. Don’t expect the order of elements to be the same as the original.

**Code:**

ratings = {‘A’, ‘B’, ‘C’, ‘D’} for rate in ratings: print(rate)

**Output:**

D

A

C

### Deleting Elements from Python Sets

To delete the element, we usually have to specify the element we want to delete. The functions used for deleting element are discard(), remove(), pop() and clear().

#### 1. discard(element)

The function deletes the specified element from the set and if the element is not present in the set, it does not return any error.

**Code:**

a={1,2,3,4} a.remove(3) print(a)

**Output:**

#### 2. remove(element)

This function is similar to discard() but the difference is that it throws an error when the specified element to delete is not found in the set.

**Code:**

a={10,20,30} a.remove(10) print(10)

**Output:**

#### 3. pop()

pop() function doesn’t take any argument and it removes an arbitrary element from the set and also returns the deleted element.

**Code:**

num_set={10,8,6,4} deleted = num_set.pop() print(deleted) print(num_set)

**Output:**

{10,4,6}

#### 4. clear()

The clear() function empties the set. It can also be used for * dictionaries*.

**Code:**

a = {1,5,10,15,20} a.clear() print(a)

**Output:**

As we know, an empty set is denoted as set() and not by {}.

### Updating a Set in Python

Set are mutable so we can remove elements and also add or update new elements to the set. We have two functions to update the values in the set. These are add() and update() methods. Let’s look at each of them.

#### 1. add(element)

The add() function takes the value as an argument which we want to add to our set and adds the element in our set.

**Code:**

fruits = {“apple”, “banana”,”cherry”} fruits.add(“strawberry”) print(fruits)

**Output:**

#### 2. update(updated_set)

The update() function can be used to add multiple values to the set at once. It takes an iterable like * lists*, set or tuple as an argument.

**Code:**

fruits = {“apple”, “banana”,} fruits.update([1,2,3]) print(fruits) fruits.update({‘cherry’, ’kiwi’ })

**Output:**

{1, 2, 3, ‘apple’, ‘banana’, ‘kiwi’}

### Frozen Sets in Python

So far we have seen sets are mutable, but now I am going to tell you about immutable sets. Frozen sets are similar to sets but the only difference is that frozen sets are immutable.

Let’s see how we can create a frozen set:

The frozenset() inbuilt function is used to create a frozen set. We can pass any iterable like list, set, * tuple*, etc and it will return us an immutable set of class type frozenset.

**Syntax:**

frozenset(iterable)

**Example: **

immutabl_set = frozenset((2,4,2,1,2,3)) print(immutable_set)

**Output:**

**Note:** Since frozenset are immutable sets, we can’t update or change any index values, the interpret will give us an error if we try to change them.

### Python Set Operations

We can perform various operations on set using functions len(), max(), min(), any(), all(), sorted(). Let’s look at each of these functions working.

#### 1. len()

The len() function is useful to know the number of elements inside an iterator. This function will return us the length of the set.

**Code:**

a={1,2,2,3,3,4} print(len(a))

**Output:**

#### 2. max() and min()

Functions like max() and min() require the set to contain the same data type elements to work with because we can’t compare integers and * strings* directly.

The function max() returns the maximum value from the set and the min() function returns the minimum value.

**Code:**

a={1,2,3,5,2,9,10} print( max(a)) print( min(a))

**Output:**

1

#### 3. any() and all()

These functions return us True or False. The any() function is used to check if any one of the values is True or not while the all() function will return True if all values result to boolean True.

**Code:**

print(any({0, False}) ) print(all({1, ‘Hello’, True}) )

**Output: **

True

#### 4. sorted()

The sorted() function takes an iterable like sets and sorts the elements in ascending order. It preserves the original array and returns a new array after sorting.

**Code:**

sorted({6,5,4,3,4,5,2,1,4})

**Output: **

Now, we will see some mathematical functions as we discussed that Python sets are related to mathematical set concept.

#### 5. union()

Let’s take an example of two sets A and B. The union operation between A and B will return all the distinctive elements in A and B.

**Code:**

A= {1, 2, 3, 4} ; B= {2, 4, 6, 4} print( A.union(B) )

**Output:**

#### 6. intersection()

The intersection operation returns the set of elements that are common in the sets that are used in intersection.

**Code:**

A= {1, 2, 3, 4} ; B= {2, 4, 6, 4} print( A.intersection(B) )

**Output:**

To operate on more sets, you can pass them with commas in an argument.

**Code:**

print({1,2,3}.intersection({2,3,4,5}, {1,3,6}) )

**Output:**

#### 7. difference()

The difference() function on sets performs the set difference operation on two or more sets.

**Code:**

print({1,2,3,4}.difference({3,4,5,6} ) ) print({1,2,3,4}.difference({3,4,5,6},{ 1,3,4,5} ) )

**Output: **

{2}

#### 8. symmetric_difference()

The function returns the unique elements in each set.

**Code:**

print({1,2,4,5,6}.symmetric_difference({ 4, 5, 6, 7, 8 }) )

**Output:**

#### 9. intersection_update(), difference_update() and symmetric_difference_update()

As we saw earlier that these functions return a new set and do not change the original set. So these functions will perform and update the original set.

**Code:**

set1 = {1,2,3} ; set2 = {2,3,4} set1.intersection_update(set2) print(set1) set1.difference_update(set2) print(set1) set1.symmetric_difference_update(set2) print(set1)

**Output:**

set()

{2,3,4}

#### 10. isdisjoint()

The isdisjoint() function takes only one argument and checks whether the two sets are completely different or not. In other words, their intersection should be null.

**Code:**

print( {1,2,3}.isdisjoint( {5,6,7} ) ) print( {1,2,3}.isdisjoint( {5,2,7} ) )

**Output:**

False

#### 11. issubset()

The issubset() function returns True if the set is a proper subset of the set given in argument.

**Code:**

print( {1,2,3}.issubset( {1,2,3,5,6,} ) ) print( {1,2,8}.issubset( {1,2,3,5,6,} ) )

**Output:**

False

#### 12. issuperset()

Like the issubset() method, this function returns True when the set is a superset of the set given in argument.

**Code:**

print( {1,2,3}.issuperset( {1, 2} ) ) print( {1,2,3}.issuperset( {1, 4} ) )

**Output:**

False

#### 13. Membership

The * python operators *‘in’ and ‘not in’ are called membership operators that checks if an element is present in the collections of elements.

**Code:**

print( “Cherry” in {“Apple”, “Cherry”, “Kiwi”} ) print( “Cherry” not in {“Apple”, “Cherry”, “Kiwi”} )

**Output:**

False

## Summary

To sum up, we first saw Python sets which holds unique values and then saw how to access them, delete and update the elements in sets. Later on, we discussed all the operations you can perform on Python sets.

So that was all about TechVidvan’s Python sets article. I hope you learned some new things today, and if you find this article helpful, do share it with your friends on social media.

Happy Learning!!