Python Set

Table Of Contents:

  1. What Is A Set Data Type?
  2. How To Create A Set In Python?
  3. Accessing Set Elements.
  4. Adding Items Into A Set.
  5. Removing Elements From The Set.
  6. Mutable Nature Of Set.
  7. Looping Through Set.
  8. Joining Sets.
  9. Deleting A Set.

(1) What Is A Set Data Type?

  1. Sets are used to store multiple items in a single variable.
  2. Set can store heterogeneous elements inside them.
  3. A Set is an unordered collection data type, that means set will store your elements in a random order.
  4. Set is a mutable data type, that means you can add, remove, update elements inside the set.
  5. Set does not allows any duplicate elements inside it. If you put duplicate also it will store only a single value of it.

(2) How To Create A Set In Python?

  • You can create a Set using curly brackets { }.
  • The elements inside the set are seperated using comma ( , ).

Example

set1 = {1,2,3,4,5,6} #Set With Integer Values

set2 = {'a','b','c','d','e'} #Set With Character Values

set3 = {1,'a',2,'b',3,'c',4,'d',5,'e'} #Set With Different Data Types

set4 = {1,1,2,2,3,3,4,4,5,5} #Set With Duplicate Elements

set5 = {'a','a','b','b','c','c','d','d','e','e'} #Set With Duplicate Elements

print(set1)

print(set2)

print(set3)

print(set4)

print(set5)
Output:

{1, 2, 3, 4, 5, 6}
{'e', 'a', 'b', 'd', 'c'}
{1, 2, 3, 'a', 4, 5, 'e', 'b', 'd', 'c'}
{1, 2, 3, 4, 5}
{'e', 'a', 'b', 'd', 'c'}

Note:

  • Here you can see that in set2 I have inserted elements in this order, {‘a’,’b’,’c’,’d’,’e’}.
  • But while printing it order has changed to {‘e’, ‘a’, ‘b’, ‘d’, ‘c’}.
  • In set4 and set5 I have added duplicate elements, but it has discarded the duplicate elements from it.

(3) Accessing Set Elements

  • As set store elements in a random order, hence using an index does not make any sense.
  • Giving an index to an element means, giving an address to that element. Set will shuffle the elements in that address.
  • So at a later point, if you search that element you will find another element present.
  • Hence indexing does not make any sense in Set.
  • It does not means that we can’t access elements from set.
  • We can use ‘for’ loop to access elements from the set.

Example-1

thisset = {1, 2, 3, 4, 5, 6}

thisset[1]
TypeError                                 Traceback (most recent call last)
<ipython-input-8-39889d4fdbfa> in <module>()
      1 thisset = {1, 2, 3, 4, 5, 6}
      2 
----> 3 thisset[1]

TypeError: 'set' object does not support indexing

Example-2

thisset = {1, 2, 3, 4, 5, 6}

for value in thisset:
    print(value)
Output:
1
2
3
4
5
6

(4) Adding Items Into Set

  • Once a set is created, you cannot change its items, but you can add new items.
  • You can not change the existing items from the set, because you don’t know at which index position the element is present.
  • You can use python’s add() method to add elements to the set.
  • To add items from another set into the current set, use the update() method.
  • The object in the update() the method does not have to be a set, it can be any iterable object (tuples, lists, dictionaries, etc.).

Example-1: add() Method

thisset = {'Ramesh','Anjali','Binod'}

print('Before:',thisset)

thisset.add('Payal')

print('After:',thisset)
Output:
Before: {'Ramesh', 'Binod', 'Anjali'}
After: {'Ramesh', 'Binod', 'Payal', 'Anjali'}

Example-2: update() Method

thisset = {"apple", "banana", "cherry"}

print('Before:',thisset)

tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print('After:',thisset)
Output:
Before: {'banana', 'cherry', 'apple'}
After: {'banana', 'pineapple', 'cherry', 'apple', 'papaya', 'mango'}

Example-3: update() Method

thisset = {"apple", "banana", "cherry"}

print('Before:',thisset)

mylist = ["kiwi", "orange"]

thisset.update(mylist)

print('After:',thisset)
Output:
Before: {'banana', 'cherry', 'apple'}
After: {'banana', 'kiwi', 'orange', 'cherry', 'apple'}

(5) Adding Items Into Set

  • To remove an item in a set, use the remove( ), or the discard() method.
  • If the item to remove does not exist, remove( ) will raise an error.
  • If the item to remove does not exist, discard( ) will NOT raise an error.
  • You can also use the pop() method to remove an item, but this method will remove the last item. Remember that sets are unordered, so you will not know what item that gets removed.
  • The return value of the pop() method is the removed item.

Example-1: remove() Method

thisset = {'Ramesh','Anjali','Binod','Payal'}

print('Before:',thisset)

thisset.remove('Binod')

print('After:',thisset)
Output:
Before: {'Ramesh', 'Binod', 'Payal', 'Anjali'}
After: {'Ramesh', 'Payal', 'Anjali'}

Example-2: remove() Throws Error If Item Is Not Present

thisset = {'Ramesh','Anjali','Binod','Payal'}

thisset.remove('Champa')
KeyError                                  Traceback (most recent call last)
<ipython-input-17-db601745f64d> in <module>()
      1 thisset = {'Ramesh','Anjali','Binod','Payal'}
      2 
----> 3 thisset.remove('Champa')

KeyError: 'Champa'

Example-3: discard() method

thisset = {1,2,3,4,5,6}

print('Before:',thisset)

thisset.discard(5)

print('After:',thisset)
Before: {1, 2, 3, 4, 5, 6}
After: {1, 2, 3, 4, 6}

Example-4: discard() don’t throws Error If Item Is Not Present

thisset = {1,2,3,4,5,6}

thisset.discard(10)

print(thisset)
Output:

{1, 2, 3, 4, 5, 6}

Example-5: pop() Method

thisset = {1,2,3,4,5,6}

print('Before:',thisset)

removed = thisset.pop()

print('After:',thisset)

print('Removed Item:',removed)
Output:

Before: {1, 2, 3, 4, 5, 6}
After: {2, 3, 4, 5, 6}
Removed Item: 1

(6) Mutable Nature Of Set

  • Mutable nature says that you can add, remove or update the original set.
  • It won’t create a new memory location when you try to edit the original set.

Example-1

thisset = {1,2,3,4,5,6}

print('Before:',id(thisset))

thisset.add(10)

print('After:',id(thisset))
Output:

Before: 2416341209608
After:  2416341209608

Note:

  • Here you can see that the memory location is the same after adding the element also.

(7) Looping Through A Set

  • You can loop through a set using for loop.

Example-1

thisset = {1,2,3,4,5,6}

for i in thisset:
    print(i)
Output:
1
2
3
4
5
6

(8) Joining Sets

  • You can use the union( ) method that returns a new set containing all items from both sets.
  • You can use the update( ) method that inserts all the items from one set into another.

Example-1: union() Method

set1 = {"a", "b" , "c"}

set2 = {1, 2, 3}

set3 = set1.union(set2)

print(set3)
Output:
{1, 2, 3, 'a', 'c', 'b'}

Example-2: update() Method

set1 = {"a", "b" , "c"}

set2 = {1, 2, 3}

set3 = set1.update(set2)

print(set3)
Output:
{1, 2, 3, 'a', 'c', 'b'}

(9) Deleting A Sets

  • You can use a del keyword to delete a set object.

Example

set1 = {"a", "b" , "c"}

del set1

print(set1)
Output:

NameError                                 Traceback (most recent call last)
<ipython-input-32-b2cc98c36b3d> in <module>()
      3 del set1
      4 
----> 5 print(set1)

NameError: name 'set1' is not defined

Leave a Reply

Your email address will not be published. Required fields are marked *