Sets are basically collection of certain items that are unordered. There is no specific order in which they are stored. In Python sets are same, but there are few differences with basic sets.

- The elements in python sets are unique, there can’t be duplicate items in python sets. If duplicate items entered, it will be ignored and final set will always contain unique elements.
- Python sets are mutable. But, its elements are immutable. Once entered items cannot be modified.
- Python set’s item cannot be accessed using indexes. There is no index attached to set items.

This tutorial explains the following examples in Python set:

- Create a Simple Set
- Create a Set with Constructor
- Create an Empty Set
- Create a Set from List
- Create a Set from Tuple
- Access a Specific Value in Set
- Add Items to a Set – Using Add Method
- Add Items to a Set – Using Update Method
- Remove Items from Set – Using Discard Method
- Remove Items from Set – Using Remove Method
- Union Operation on Sets
- Intersection Operation on Sets
- Difference Operation on Sets
- Symmetric Difference of Two Sets
- Compare two Sets
- Membership Test on Sets
- Iterating on Set
- Clearing a Set
- Interesting Problem Solved using Sets
- Full Example Code of Sets – sets.py

### 1. Create a Simple Set

Python sets can be created by simply writing the items within curly braces.

>>> primes={3,5,7,9,11,13} >>> type(primes) <class 'set'>

Note: Keep in mind that Python dictionaries also uses {} in declaration. But, in the above example, we’ve created a set as indicated by the type command output.

For Python dictionaries, refer to this: Python Dictionary Examples – Create, Update and Delete Elements

### 2. Create a Set with Constructor

Use set as shown below and pass the initial string as constructor.

In the following example, we are purposefully adding another “s” in front of “stuff”, which will be ignored by the set. It will take only one “s” even when we gave more than one.

>>> unique=set("thegeeksstuff"); >>> unique {'h', 't', 'u', 's', 'f', 'e', 'g', 'k'} >>> type(unique) <class 'set'>

### 3. Create an Empty Set

The following is an incorrect way of creating an empty set. This will create an empty dictionary:

>>> empty={} >>> type(empty) <class 'dict'>

The correct way to create is shown below. To create an empty set, use the set method with empty constructor as shown below.

>>> empty=set(); >>> type(empty) <class 'set'>

While trying to create empty set, use constructor method. Otherwise using 1st method will make an empty dictionary instead.

### 4. Create a Set from List

First create a list as shown below:

>>> primesList=[3,5,7,11,13,17];

To learn more about list, refer to this: Python List Examples – Insert, Append, Length, Index, Remove, Pop

Next, create a set using the above list:

>>> primeSet=set(primesList) >>> type(primeSet) <class 'set'> >>> primeSet {3, 5, 7, 11, 13, 17}

### 5. Create Set from Tuple

First, create a tuple as shown below.

>>> p=(3,5,7,11,13); >>> p (3, 5, 7, 11, 13) >>> type(p) <class 'tuple'>

To learn more about tuples, refer to this: 17 Practical Python Tuples Examples

Next, create a set from the above tuple:

>>> primes=set(p); >>> p (3, 5, 7, 11, 13) >>> type(primes) <class 'set'> >>> primes {3, 5, 7, 11, 13}

### 6. Access a Specific Value in Set

Set elements cannot be accessed specifically, there is no index attached to it. We cannot access elements of set.

>>> primes = {3, 5, 7, 11, 13} >>> primes[1] Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> primes[1] TypeError: 'set' object does not support indexing

### 7. Add Items to a Set – Using Add Method

Items can be added to set using two methods add and update. Add method can insert single element but update method can insert tuple, lists too.

>>> primes={3,5,7,11}; >>> primes {11, 3, 5, 7} >>> primes.add(19); >>> primes {3, 5, 7, 11, 19}

### 8. Add Items to a Set – Using Update Method

The following will add the items from the plist to the primes set.

>>> plist=[12,14,15,16]; >>> primes.update(plist); >>> primes {3, 5, 7, 11, 12, 14, 15, 16, 19}

### 9. Remove Items from Set – Using Discard Method

Items can be removed from set using discard and remove method. While removing items, if item does not exist, remove reports and error while discard doesn’t.

>>> primes {3, 5, 'santosh', 7, 11, 12, 14, 15, 16, 19} >>> primes.discard("santosh") >>> primes {3, 5, 7, 11, 12, 14, 15, 16, 19} >>> primes.discard("santosh");

While trying to remove already removed item, discard does not report an error.

### 10. Remove Items from Set – Using Remove Method

Currently primes set has the following values.

>>> primes {3, 5, 7, 11, 12, 14, 15, 16, 19}

The following will remove the item with value 11 from the primes set.

>>> primes.remove(11);

As you see below, we don’t see item with value 11 anymore in primes set.

>>> primes {3, 5, 7, 12, 14, 15, 16, 19} >>> primes.remove(11); Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> primes.remove(11); KeyError: 11

Remove method reported error when trying to remove element which does not exist.

### 11. Union Operation on Sets

Union operation (|) will create a new set with distinct items from both the sets.

>>> prime1={3,5,7,11}; >>> prime2={3,5,7,11,13,17,19} >>> primes=prime1 | prime2 >>> primes {3, 5, 7, 11, 13, 17, 19}

### 12. Intersection Operation on Sets

Intersection operation (&) will create a new set with items common to both the sets.

>>> prime1={3,5,7,11}; >>> prime2={3,5,7,11,13,17,19} >>> primes=prime1 & prime2 >>> primes {3, 11, 5, 7}

### 13. Difference Operation on Sets

Difference operation will create a new set containing elements that are in first set but not in the second set

>>> prime2={3,5,7,11,13,17,19} >>> prime1={3,5,7,11}; >>> primes=prime2-prime1 >>> primes {17, 19, 13}

### 14. Symmetric Difference of Two Sets

Symmetric difference of two sets will create a new set containing elements from both the sets except common elements.

>>> prime2={3,5,7,11,13,17,19} >>> prime1={3,5,7,11,91,101}; >>> primes=prime2 ^ prime1 >>> primes {17, 19, 101, 91, 13}

### 15. Compare two Sets

Using comparison we can check if one set is superset or subset or equal to another set.

>>> prime1={3,5,7,11,91,101}; >>> prime={3,5,7,11,91,101}; >>> test=prime==prime1 >>> test True >>> prime1={3,5,7,11,91,101}; >>> prime2={3,5,7,11,13,17,19} >>> test=prime2<prime1 >>> test False >>> prime2={3,5,7,11,13,17,19} >>> prime1={3,5,7,11,91,101}; >>> prime1={3,5,7,11}; >>> test=prime2<prime1 >>> test False >>> test=prime2>prime1 >>> test True

### 16. Membership Test on Sets

We can test if an element exist or not in specified set.

>>> prime1={3,5,7,11,91,101}; >>> test= 3 in prime1 >>> test True >>> test=13 in prime1 >>> test False

### 17. Iterating on Set

Let us use the following primes set for this example.

>>> primes={3,5,7,11,91,101}; use for loop to loop through the set elements. >>> for prime in primes: print(prime); 3 5 101 7 11

To learn more about for loop, refer to this: 12 Essential Python For Loop Command Examples

### 18. Clearing a Set

Using clear method, all the items of set can be deleted.

>>> prime1 {3, 5, 101, 7, 11, 91} >>> prime1.clear() >>> prime1 set()

### 19. Interesting Problem Solved using Sets

Problem statement: given a list of integers, print all the distinct elements.

Using sets we can solve this problem in single line of code.

>>> number = [1,2,3,4,5,2,3,4,7,8,9,8,12,13,14,14,19] >>> number [1, 2, 3, 4, 5, 2, 3, 4, 7, 8, 9, 8, 12, 13, 14, 14, 19] >>> print (set(number)) {1, 2, 3, 4, 5, 7, 8, 9, 12, 13, 14, 19}

This was a use case, similarly sets can be useful in other scenarios.

### 20. Full Example Code of Sets – sets.py

Create a sets.py file

vi sets.py

Copy/paste the following into sets.py and execute it for your testing.

#1) Creating set primes={3,5,7,9,11,13} type(primes) # 2) Creating set with constructor unique=set("thegeeksstuff"); unique # 3) Creating empty set empty={} type(empty) empty=set(); type(empty) #4) Creating set from List primesList=[3,5,7,11,13,17]; primeSet=set(primesList) type(primeSet) primeSet # 5) Creating set from tuple p=(3,5,7,11,13); primes=set(p); type(primes) primes # 6) Accessing values in Set Primes = {3, 5, 7, 11, 13}; #Primes[1]; # uncommenting this throw error #7) Using Add method primes={3,5,7,11}; primes.add(19); primes # 8) Using update method plist=[12,14,15,16]; primes.update(plist); primes #9) Using discard primes={3, 5, 'santosh', 7, 11, 12, 14, 15, 16, 19}; primes.discard("santosh") # 10) Using remove primes = {3, 5, 7, 11, 12, 14, 15, 16, 19} primes.remove(11); primes; # 11) Union operation on sets prime1={3,5,7,11}; prime2={3,5,7,11,13,17,19} primes=prime1 | prime2 primes # 12) Intersection operation on Sets prime1={3,5,7,11}; prime2={3,5,7,11,13,17,19} primes=prime1 & prime2 primes # 13) Difference operation on sets prime2={3,5,7,11,13,17,19} prime1={3,5,7,11}; primes=prime2-prime1 primes # 14) Symmetric difference prime2={3,5,7,11,13,17,19} prime1={3,5,7,11,91,101}; primes=prime2 ^ prime1 primes # 15) Compare two sets prime1={3,5,7,11,91,101}; prime={3,5,7,11,91,101}; test=prime==prime1 test prime1={3,5,7,11,91,101}; prime1={3,5,7,11}; test=prime2<prime1 test #16) Membership test on sets prime1={3,5,7,11,91,101}; test= 3 in prime1 test # 17) Iterating on set primes={3,5,7,11,91,101}; for prime in primes: print(prime); # 18) Clearing a set prime1 {3, 5, 101, 7, 11, 91} prime1.clear() #19) interesting problem number = [1,2,3,4,5,2,3,4,7,8,9,8,12,13,14,14,19] print (set(number))

Executing the above sets.py will display the following output. Study the above code properly to understand why you are getting the following output.

$ python sets.py 3 5 7 11 91 101 set([1, 2, 3, 4, 5, 7, 8, 9, 12, 13, 14, 19])

{ 1 comment… add one }

The following code works perfectly ok –

mylist=[10,20,30]

myset=set(mylist)

print(myset)

but the following does not –

mylist=[10,20,30]

myset=set({10,20,30,mylist})

print(myset)

______________________________

Please tell the reason.