Sets in Python | Python Programming

Sets in Python: Set in python is another type of data type which is represented by curly braces {} same as the dictionary. Sets are un-ordered and un-indexed data type. However, Set itself is mutable. We can add or remove items from sets. Sets can also be used to perform mathematical set operations like union, intersection, etc. In Sets, we are not sure in which order the items will appear.

How to create Set: A Set in python can be defined by {} curly braces. It can contain any number of items of different data types i.e. (integer, float, tuple etc.). But it cannot contains mutable data types i.e. a list, dictionary etc.

Syntax:

#Sets Syntax
test = {"papaya", "guava", "oranges"}
print(test)

# output
# {'oranges', 'guava', 'papaya'}

Note: A Set cannot contain duplicate items. However, Set is mutable means we can add or remove data from a Set.

sets-in-python

Operations on Sets

Below are some available set methods in python, that are applicable on sets:

1). Accessing ElementsAs already mentioned above that sets are un-indexed data type, means its values doesn’t have an index. So, it is not possible to access the item inside sets using indexing. But we can iterate over the set items using for loop.  Also, we can use a membership operator along with for loop.

Example

#Sets example
test = {"guava", "mango", "papaya"}
for data in test:
  print(i)

# output
# guava
# mango
# papaya

Explanation:

  • Here we have defined a set test with some values initialized.
  • Next, we used for loop with in membership operator.
  • For loop iterate over each element of set test. It iterate like ‘for each item of test in data’.
  • It means the for loop iterate on each item of test one by one and setting the single item in the data variable.
  • In for loop, the index is incremented to +1 by default. Hence after every successful iteration, the index is auto-increment by 1.
  • We keep on printing the element that is getting stored in data after each successful iteration.
  • Hence, the output is displayed.
  • Learn more about for loop in detail.

2). Updating or Changing itemsOnce the set has been created, then we cannot change its values or element. But we can add new elements/values to them. This means we can add or remove items to set but do not update the existing elements of set. We have two methods that are used to add more items to our set.

  • add(): This method is used to add one item to set.
  • update(): update() set methods in python is used to add more than one item to set.

Example 1: using add() method

#Adding item to sets
test = {"papaya", "mango", "kiwi"}
test.add("guava")
print(test)

# output
# {'guava', 'mango', 'kiwi', 'papaya'}

Example 2: using update() method

#Adding items to sets
test = {"guava","kiwi","sweet-potato"}
test.update(["papaya","mango","berry"])
print(test)

# output
# {'papaya', 'mango', 'potato', 'kiwi', 'berry', 'guava'}

Explanation:

  • In example 1, we added one item to set using add() method of set. The limitation of add() method is that we can add only a single item to set in a single step.
  • In example 2, we added 3 items to set using the update() method of a set. We can add multiple items to set in a single step.
  • Hence we can perform the operation of adding elements to the Set.

3). Remove or DeleteThere are two methods available in python to remove elements from sets. These two methods are:

  • remove()
  • discard()

Example 1: Using remove()

#Removing sets elements

test = {"guava", "mango", "berry"}
test.remove("guava")
print(test)

# output
# {'mango', 'berry'}

Example 2: Using discard()

#Removing elements from sets
test = {"guava", "papaya", "berry"}
test.discard("papaya")
print(test)

# output
# {'guava', 'berry'}

4). PoP() MethodThis method is used to remove the last element from a set. As the sets are an unordered set of data types, so we do not know, when we use the pop() method, which element is going to remove. It is random data removal.

Example

#Pop method in Sets()
test = {"guava", "papaya", "berry"} 
test.pop() 
print(test) 

# output
# {'guava', 'papaya'}

Explanation:

  • pop() method of set in Python participates in random data removal.
  • This means when we use the pop() method on set type data structure. Then the data removal is random as set is an un-ordered data type.

5). Del keywordThe del keyword of Python is used to delete the complete set.

Example

#Del method in Sets()
test = {"guava", "papaya", "berry"} 
print(test)

# output
# {'guava', 'papaya'}

# Deleting Set
del test 
print(test)

# output
# Traceback (most recent call last): File "./prog.py", 
# line 10, in NameError: name 'test' is not defined

Explanation:

  • In the first line, we created a set and also initialized it with some values.
  • Next, we printed the set and hence the output is obtained.
  • As discussed, the del keyword is used to delete the complete set sequence. Hence we used the del keyword followed by the set name test.
  • Next, we tried to print the same set. But this time it results in an error i.e. name test is not defined.
  • Hence, it means the set is deleted.

6). Joining two setsWe can also join two or more sets using available sets methods. There are two types of methods that are used to join sets:

1). Set Union(): The meaning of union in mathematic is to get all the values of the given sets. Suppose set1 and set2 have been given and we have to perform the operation of union on both sets. Follow below given example:

sets in python

Example 1: Using union() method.

#union() in sets
set1 = {"c", "b" , "a",1}
set2 = {3, 2, 1,1}
test = set1.union(set2)
print(test)

# output
# {1, 2, 3, 'c', 'a', 'b'}

Example 2: Using |operator.

#using | operator 
set1 = {"c", "b" , "a",1} 
set2 = {3, 2, 1,1} 
print(set1 | set2)

# output
# {1, 2, 3, 'c', 'a', 'b'}

Explanation:

  • Union operation on sets can be performed by union() method as well as | operator. Its implementation has been elaborated in the above-given examples example1 and example2.
  • Sets can only carry unique values. Hence we can observe that in the example1 and example 2. The resulting output does not carry the repeated values.

2). Set Intersection(): The meaning of intersection in mathematics is to get only those values that are common in the given sets. Suppose set1 and set2 have been given and we have to perform the operation of intersection on both sets. The intersection of set1 and set2 is a set of elements that are common in both sets. Follow below given example:

sets in python

# Intersection of sets
set1 = {3, 2, 1, 5, 6}
set2 = {2, 6, 5, 3, 3}
print(A & B)

# use & operator
# output: 
# {4, 5}

Explanation:

  • The intersection of set1 and set2 is a set of elements that are common in both sets.
  • & operator is also used to perform intersection operation on sets.
  • Set ignores the repeating elements.

7). Constructor set()A constructor is also available in sets to create sets explicitly:

Example

#Set() Constructor
test = set(("mango", "guava", "pears")) 
print(test)

# output
# {'pears', 'mango', 'guava'}

8). Clear() method: Clear() method in python is used to clear the elements of the set completely.

Example

#clear method
test = {"car", "truck", "bus"}
test.clear()
print(test)

# output
# {}

Summary of available set methods in python

We already learnt about available set methods in python. Below is the summary given for a quick overview of available set methods in python.

Method Name Description
copy() It returns a copy of the set.
clear() It removes all the elements from the set.
discard() It removes the specified or selected item from the set.
add() It is used to add an element to the set.
pop() Removes an element from the set.
intersection() It returns a set(), which is the intersection of two sets.
remove() It is used to remove the specified element from the set.
union() It returns a set, which contains the union of sets.
update() It updates the set with the union this set and another set.