Python set operations

Python set operations

Instructor-svgAl-Mamun Sarkar
Mar 24 , 2020

Set is a collection of elements that don't allow duplicate value. An item can be added multiple times in a list but can't do that in a set.

Python set operations. Add item to set, Update an item, remove items. Sets add(), update(), remove(), discard() functions.

Create a Set:

unique_numbers = {"one", "tow", "three"}

Create set using set() Constructor:

unique_numbers = set(("one", "tow", "three"))
print(unique_numbers)

 

Getting the length of the set:

unique_numbers = {"one", "tow", "three"}
len(unique_numbers)

 

Check if an item present in the set:

unique_numbers = {"one", "two", "three", "four", "five"}
print( 'four' in unique_numbers )

 

Looping a set:

unique_numbers = set(("one", "tow", "three"))
for number in unique_numbers:
    print(number)

 

Adding Item to a set:

unique_numbers = {"one", "tow", "three"}
unique_numbers.add("fout")
print(unique_numbers)

Output:

{'three', 'fout', 'one', 'tow'}

 

Adding two sets:

unique_numbers = {"one", "tow", "three"}
others = {"fout", "file"}
unique_numbers.update(others)
print(unique_numbers)

Output:

{'file', 'fout', 'one', 'three', 'tow'}

 

Remove item from the set:

unique_numbers = {"one", "tow", "three", "four", "five"}
unique_numbers.remove("three")
print(unique_numbers)

Output:

{'one', 'four', 'tow', 'five'}

 Remove item from the set using discard:

unique_numbers = {"one", "tow", "three", "four", "five"}
unique_numbers.remove("three")
print(unique_numbers)

Output:

{'one', 'four', 'tow', 'five'}

 

 Remove the last item using pop():

The pop() method remove item randomly because the set is not an ordered collection.

unique_numbers = {"one", "tow", "three", "four", "five"}
unique_numbers.pop()
print(unique_numbers)

 

Clear the set:

unique_numbers = {"one", "tow", "three", "four", "five"}
unique_numbers.clear()
print(unique_numbers)

 

 Delete the set:

unique_numbers = {"one", "tow", "three", "four", "five"}
del unique_numbers

 

Some Examples:

A = {'orange', 'banana', 'pear', 'apple', 'apple'}
print(type(A))
print(A)

A.add("where")
print(A)

A.update('banana', 'Mango')
print(A)

A.remove("where")
print(A)

A.discard("where")
print(A)

B = set('apple')
print(type(B))
print(B)

Output:


{'banana', 'apple', 'pear', 'orange'}
{'apple', 'where', 'banana', 'orange', 'pear'}
{'o', 'apple', 'a', 'where', 'b', 'banana', 'M', 'g', 'orange', 'n', 'pear'}
{'o', 'apple', 'a', 'b', 'banana', 'M', 'g', 'orange', 'n', 'pear'}
{'o', 'apple', 'a', 'b', 'banana', 'M', 'g', 'orange', 'n', 'pear'}

{'p', 'a', 'e', 'l'}

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram