Python Sets

Set is collection of unique and unordered elements. That are capable to store any kind of value but there is not possible to use one set within of another set. that are contain a value of immutable type. sets are useful to perform standard operating within the two sets like union, set difference, interaction etc.

setVariable={element1,element2,...,elementN}

set element are exist within curly brackets ({}). and element is separated by commas (,). If there is not given any element so that means that is empty set (element is optional).

#defined python sets
setItem={1,2,3,4,5,6}

setQnique={True,False,True,False,1,0}

setLanguage={"C","C++","Python","Java","etc"}

emptySet={}

#display Sets element
print(setItem)
print(setQnique)
print(setLanguage)
print(emptySet)
Output
{1, 2, 3, 4, 5, 6}
{0, 1}
{'Python', 'Java', 'C', 'etc', 'C++'}
{}

Note that in this program are defined 4 different sets. first set is containing of unique 6 elements. second set (setQnique set) are interesting there are provide initial 6 element but element are repeating . so it will created unique element sets. this 6 element are (true,false,1,0) are 4 different element by (True are internally equal to 1) and (False are internally equal to 0) so only 2 unique element of this set. view in this image of structure of all sets.

Defined Python Sets

Set 3(setLanguage set) are exist 5 unique elements. but that set elements is in a unordered format. so every sequences of elements combination are similar.

Set 4 (emptySet) are not define any element so there is an empty set.

There is possible to convert python list and python tuple to python set of using set function. for example

#defined a list
listItem=[1,2,3,4,5,6,5,6]

#define a tuple
tupleItem=(11,22,33,22)

#convert python list to python set 
set_listItem=set(listItem)

#convert python tuple to python set 
set_tupleItem=set(tupleItem)

#display values
print(listItem)
print(tupleItem)
print(set_listItem)
print(set_tupleItem)
Output
[1, 2, 3, 4, 5, 6, 5, 6]
(11, 22, 33, 22)
{1, 2, 3, 4, 5, 6}
{33, 11, 22}

In this program listItem is collection of list, and tuplItem is collection of tuple. those two collection are use to in a set() function and make a new set.

Create set using list tuple

Note that set() function is create new set by using of all unique element. There are not exist duplicate element. View that tuples and list are pairs of index and value. set are use only value.

so how to check value of variable?. python is providing type() function to display variable type. view this example.

#defined a list
listItem=[1,2,3,4,5,6,5,6]

#define a tuple
tupleItem=(11,22,33,22)

#convert python list to python set 
set_listItem=set(listItem)

#convert python tuple to python set 
set_tupleItem=set(tupleItem)

#display variable type
print(type(listItem))
print(type(tupleItem))
print(type(set_listItem))
print(type(set_tupleItem))
Output
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'set'>

Modified set elements

modified set means, add new item, update existing item and remove particular elements etc.

Add new items

There are two way to add new item on exist set. There are two function are available such as add() and update() to add item in set. for example.

#defined a set
setItem={1,2,3}

print("Initial set element")
print(setItem)

#add function example
setItem.add(11)
setItem.add(22)
setItem.add(33)
setItem.add(1) #Already exist

print("After add function ")
print(setItem)

setItem.update([1,9,7]) #add new 9,7
setItem.update([100,200])
setItem.update(["In","Out"])
setItem.update([11.50,33.10])

print("After update function ")
print(setItem)
Output
Initial set element
{1, 2, 3}
After add function 
{1, 2, 3, 33, 11, 22}
After update function 
{1, 2, 3, 33, 100, 33.1, 7, 200, 9, 11, 11.5, 22, 'In', 'Out'}

In given this program are given two different approach to add item in a set.

add() function are used to adding single element to existing set. of given item value already exist then it will not insert this element. and also not produce any error.

update() function capable to add single or multiple items in given set. if given element are exist then it will not includes that element (dropping duplicates elements).

Delete existing item

There are four special methods are available to remove element of sets. there are as follows.

pop() function : This function is remove one arbitrary element. because set is collection of unordered element.

#defined a set
setItem={"coin","dollar","rupee",2019,2020,2021,True}
#Initial element
print(setItem)

#remove one element
setItem.pop()
print(setItem)

#remove one element
setItem.pop()
print(setItem)
Output
{True, 2019, 2020, 2021, 'rupee', 'dollar', 'coin'}
{2019, 2020, 2021, 'rupee', 'dollar', 'coin'}
{2020, 2021, 'rupee', 'dollar', 'coin'}

In this program are performing two pop operation on given set. There are total 7 element of exist in given set initially.

python pop set items

After perform first pop operation of this set it will remove one element. position of this element are not predefined.

After first pop operation

In similar way second pop operation are remove one element.

After second pop operation

pop() method are remove one element. if set is already empty so it will produce an error. see this example.

#defined a set
setItem={1,2}
#Initial element
print(setItem)

#remove one element
setItem.pop()
print(setItem)

#remove one element
setItem.pop()
print(setItem)

#try to remove one element
setItem.pop() # error in this case
print(setItem)
Output
{1, 2}
{2}
set()
Traceback (most recent call last):
  File "test.py", line 15, in <module>
    setItem.pop() # error in this case
KeyError: 'pop from an empty set'

remove() function : This function are used to remove specific value of given set.

#defined a set
setItem={1,2,3,4}

#remove value 1
setItem.remove(1)
print(setItem)

#remove value 4
setItem.remove(4)
print(setItem)
Output
{2, 3, 4}
{2, 3}

This remove() function are very similar to pop() function. but it will take one parameter to removing value. if value are exist then it will remove this value. otherwise that are produced an error. see this example

#defined a set
setItem={1,2,3,4}

#remove value 1 
setItem.remove(1) #okay
print(setItem)

#remove value 14
setItem.remove(14) #not okay
print(setItem)
Output
{2, 3, 4}
Traceback (most recent call last):
  File "test.py", line 9, in <module>
    setItem.remove(14) #not okay
KeyError: 14

In this example given key value are not exist in set. so it will produce key value error.

discard() function : discard is also used to remove specific key value in existing set. the advantage of this function it will work of both cases. if element are exist when remove that element. if element are not defined then simply dropped this operation (not produce an error).

#defined a set
setItem={1,2,3,4}

print(setItem)

#remove value 1 
setItem.discard(1) #okay
print(setItem)

#remove value 1 
setItem.discard(4) #okay
print(setItem)

#remove value 14
setItem.discard(14) #value not found 
print(setItem)

#remove value 1 
setItem.discard(3) #okay
print(setItem)
Output
set([1, 2, 3, 4])
set([2, 3, 4])
set([2, 3])
set([2, 3])
set([2])

Note that value 14 are not exist in given set.

clear() function : this are remove all element of existing set. that is similar to assign empty set.

#defined a set
setItem={1,4,2}

print(setItem)

#clear set value
setItem.clear() 
print(setItem)

logicalSet={1,2,3}

#alternate of clear() function
logicalSet={}
print(logicalSet)
Output
set([1, 2, 4])
set([])
{}


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved