Advertisement

In our previous Python article, we have explained a collection data types like tuple and list. Moving on in this tutorial, we are going to explain another collection data type provided by Python -

Unlike the

## Important properties of a Set

- A set is
*mutable*even i.e. we can insert a new item to it and can delete an existing item from it. - We cannot store duplicate values in a set.
- Because the order in which items of a set are stored is
*arbitrary*, so there is no concept of accessing an item of a**set**using an*index*position. ## Methods of the Set collection data type

## How to create a set in Python?

Now let us discuss important methods of

Methods | Description |
---|---|

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

discard() |
Removes an item from the set. |

clear() |
Clears/removes all the items in a set. |

remove(item) |
Removes an item from the set, if unsuccessful raises KeyError. |

pop() |
Removes an arbitrary item from the set, if unsuccessful raises KeyError. |

copy() |
Returns copy of a set. |

update(s) |
Adds all of the items in set s to the invoked set. |

union(s) |
Returns a new set which has items of the invoked set and the set s. |

intersection(s) |
Returns a new set which has common items in both the invoked set and the set s. |

symmetric_difference(s) |
Returns a new set which has unique items in both the invoked set and the set s. |

difference(s) |
Returns a new set which has items only in the invoked set and not in the set s. |

union_update(s) |
Updates the invoked set and adds the items of the set s to it. |

intersection_update(s) |
Updates the invoked set to contain only the items common in it and in the set s. |

symmetric_difference_update(s) |
Updates the invoked set to contain only the unique items in it and in the set s. |

difference_update(s) |
Updates the invoked set to contain the items which are not in the set s. |

In order to create a

```
#Python - Creating a set with items
set_ex ={'Never give up', 19.2, -29, 'A'}
print(set_ex)
```

`{19.2, 'A', 'Never give up', -29}`

In the example above, we have created a

Another way to create a set of items is by calling the built-in

- If this function is passed
*zero*arguments(*no argument*), it returns an*empty set*. - If this function is passed a
**set, list**or a**dictionary**as an argument, it converts it into a**set**and returns it. - With any other kind of object as its argument, it tries to convert it to a
**set**and returns it.

```
#Python - Creating a set with items using set() function
# Creating an empty set by calling set() with no argument.
set_ex = set()
# Printing the first set
print('First set : ', set_ex)
# Creating a set by calling set() with a set as its argument
set_ex2 = set({'Never give up', 19.2, -29, 'A'})
# Printing the third set
print('Second set : ', set_ex2)
# Creating a set by calling set() with a tuple as its argument
set_ex3 = set(('Never give up', 19.2, -29, 'A'))
# Printing the third set
print('Third set : ', set_ex3)
# Creating a dictionary
dict1 = {
4:'Fourth',
3:'Third',
'two':'Second',
'one':'First',
5:'Fifth'
}
# Creating a set by calling set() with a dictionary as its argument i.e. keys of a dictionary will be added to set
set_ex4 = set(dict1)
# Printing the fourth set
print('Fourth set : ', set_ex4)
```

```
First set : set()
Second set : {'Never give up', 'A', 19.2, -29}
Third set : {'Never give up', 'A', 19.2, -29}
Fourth set : {'two', 3, 4, 5, 'one'}
```

Advertisement

We can iterate over the items in a

```
#Python - Iterating over items in a set
# Creating a set with items
set_ex ={'Never give up', 19.2, -29, 'A'}
# Using for loop to iterate over items in a set
for val in set_ex:
print(val)
```

```
A
Never give up
19.2
-29
```

As you can see in the output, items are stored in an arbitrary order as compared to the order of their declaration.

We can perform the

Operations | Description |
---|---|

Union |
Performs addition of two sets, using | operator and returns a new set. |

Intersection |
Gives the common items in two sets, using & operator and returns a new set. |

Difference |
Gives us the items present in one set but not in another, using - operator and returns a new set. |

Symmetric Difference |
Gives us unique items present in two sets, using ^ operator and returns a new set. |

```
#Python - Set Operations Example
# First set
set1 ={'Never give up', 10, -29, 'A', 1}
# Second set
set2 ={1, 20, 10}
print('First set : ', set1)
print('Second set : ', set2)
# Union of two sets using | operator i.e. adding items of two sets
print('Union of two sets : ', set1 | set2)
# Intersection of two sets using & operator i.e. items similar in two sets
print('Intersection of two sets : ', set1 & set2)
# Difference of two sets using - operator i.e. items in first set but not in second set
print('Difference between first and second set : ', set1 - set2)
# Symmetric difference of two sets using ^ operator i.e. unique items in both the first and second set
print('Symmetric difference between two sets : ', set1 ^ set2)
```

```
First set : {1, -29, 10, 'A', 'Never give up'}
Second set : {1, 10, 20}
Union of two sets : {1, -29, 20, 'Never give up', 10, 'A'}
Intersection of two sets : {1, 10}
Difference between first and second set : {'Never give up', -29, 'A'}
Symmetric difference between two sets : {-29, 20, 'Never give up', 'A'}
```

Apart from using the operators discussed in our last example, we can also perform

```
#Python - Set Operations Example
# First set
set1 ={'Never give up', 10, -29, 'A', 1}
# Second set
set2 ={1, 20, 10}
print('First set : ', set1)
print('Second set : ', set2)
# Union of two sets using union() method
print('Union of two sets : ', set1.union(set2))
# Intersection of two sets using intersection() method i.e. items similar in two sets
print('Intersection of two sets : ', set1.intersection(set2))
# Difference of two sets using difference() method i.e. items in first set but not in second set
print('Difference between first and second set : ', set1.difference(set2))
# Symmetric difference of two sets using symmetric_difference() method i.e. unique items in both the first and second set
print('Symmetric difference between two sets : ', set1.symmetric_difference(set2))
```

```
First set : {1, 'Never give up', -29, 10, 'A'}
Second set : {1, 10, 20}
Union of two sets : {1, 'A', 'Never give up', -29, 20, 10}
Intersection of two sets : {1, 10}
Difference between first and second set : {'A', 'Never give up', -29}
Symmetric difference between two sets : {'Never give up', -29, 'A', 20}
```

Once we have declared a set with its items, it is mutable i.e. we can add new items to it by using the

```
#Python - Iterating over items in a set
# Creating a set with items
set_ex ={'Never give up', 19.2, -29, 'A'}
print('Original set : ', set_ex)
# Calling add() method to add new item to a set
set_ex.add('2019')
print('Adding 2019 to set : ', set_ex)
# Calling add() method to add an existing item to a set
set_ex.add(-29)
print('Adding -29 to set : ', set_ex)
# Calling remove() method to remove an existing item from a set
set_ex.remove(19.2)
print('Removing 19.2 from set : ', set_ex)
# Calling discard() method to discard an existing item from a set
set_ex.discard(-29)
print('Discarding -29 from set : ', set_ex)
```

```
Original set : {19.2, 'Never give up', 'A', -29}
Adding 2019 to set : {-29, '2019', 'A', 19.2, 'Never give up'}
Removing 19.2 from set : {-29, '2019', 'A', 'Never give up'}
Discarding -29 from set : {'2019', 'A', 'Never give up'}
```

Though both the methods

When the

```
#Python - Difference between discard() and remove() method of set
# Creating a set with items
set_ex ={'Never give up', 19.2, -29, 'A'}
print('Original set : ', set_ex)
# Calling discard() method to discard a not existing item from a set
set_ex.discard(0)
print('Discarding 0 from set : ', set_ex)
# Calling remove() method to remove a not existing item from a set returns an KeyError
set_ex.remove(10)
print(set_ex)
```

```
Original set : {19.2, 'A', 'Never give up', -29}
Discarding 0 from set : {19.2, 'A', 'Never give up', -29}
Traceback (most recent call last):
File "D:/Python/Python37/set3.py", line 15, in
```
set_ex.remove(10)
KeyError: 10

Though the methods

```
#Python - Using pop() method to remove a random item from set
# Creating a set with three items
set_ex ={'Never give up', -29, 'A'}
print('Original set : ', set_ex)
# Calling pop() removes a random element
set_ex.pop()
print('Modified set after calling pop() : ', set_ex)
# Calling pop() removes a random element
set_ex.pop()
print('Modified set after calling pop() : ', set_ex)
# Calling pop() removes a random element and the set will be empty now
set_ex.pop()
print('Modified set after calling pop() : ', set_ex)
# Calling pop() method on an empty set will return an error i.e. KeyError
set_ex.pop()
print('Modified set after calling pop() : ', set_ex)
```

```
Original set : {'Never give up', -29, 'A'}
Modified set after calling pop() : {-29, 'A'}
Modified set after calling pop() : {'A'}
Modified set after calling pop() : set()
Traceback (most recent call last):
File "D:/Python/Python37/set4.py", line 25, in
```
set_ex.pop()
KeyError: 'pop from an empty set'

So far, we have studied the properties of the

We could create a frozen set by calling the

```
#Python - Frozenset example
# Creating a frozen set by calling frozenset() function
frozen_set_ex = frozenset({'Never give up', -29, 'A'})
# Printing items of a frozenset
print(frozen_set_ex)
```

`frozenset({'Never give up', 'A', -29})`

Functions | Description |
---|---|

max() |
Returns the maximum value in a set. |

min() |
Returns the minimum value in a set. |

len() |
Returs the total length of a set. |

sum() |
Returns sum of all items in a set. |

sorted() |
Returns a sorted copy of a set. |

any() |
Returns true if any element in a set is true, else false. |

all() |
Returns true if all elements in a set are true, else false. |

```
#Python - Functions working with sets
#First set
set1 ={19, -20, 209, 799.99, -15.4}
#Second set
set2 =(1, True, False, 0) # 1 is boolean true, 0 for boolean false
# True(with capital T) is boolean true, False(with capital F) is boolean false
#Printing sets
print('Set1 : ', set1)
print('Set2 : ', set2)
#Using max() function with a set.
print('Maximum value in set1 : ', max(set1))
#Using min() function with a set.
print('Minimum value in set1 : ', min(set1))
#Using sum() function with a set.
print('Sum of values in set1 : ', sum(set1))
#Using sorted() function with a set.
print('Sorted copy of set1 : ', sorted(set1))
#Using all() function with a set.
print('all() boolean true values in set2 : ', all(set2))
#Using any() function with a set.
print('any boolean true value in set2 : ', any(set2))
```

```
Set1 : {-20, 209, -15.4, 19, 799.99}
Set2 : (1, True, False, 0)
Maximum value in set1 : 799.99
Minimum value in set1 : -20
Sum of values in set1 : 992.59
Sorted copy of set1 : [-20, -15.4, 19, 209, 799.99]
all() boolean true values in set2 : False
any boolean true value in set2 : True
```

Advertisement

Advertisement

Please check our latest addition

** C#, PYTHON and DJANGO**

Advertisement