Skip to main content

Set in python on Python hunter blog by pran sukh

The set can contain elements or members of anything: numbers, characters, words, names, letters of the alphabet, even other sets and tuples. Sets are usually denoted with capital letters. Set is a data type in python and can hold any number of elements and any type of data in it. Even set data type is similar to other data types in python like list and tuple still there are some differences.
  • Only unique object will be inserted as set element, duplicate or repeated elements will be removed from set object.
  • Set object can not have list and dictionary object as element but we can pass a single list or dictionary object to Set() method and turn the list or dictionary into individual elements. This is the shortest method to remove the duplicates from list object. No need to filter the duplicate from dictionary object as it is already taken in care by dictionary.
  • It is wise and error free to have tuple object as set's elements.
  • Even the set contain the immutable object(s) as element still the set object is mutable and can be altered at run time.
  • Set can contain another set as element.



 Follow Python Hunter on youtube   Follow Python Hunter on twitter Follow on tumbl ( at your own risk ) check profile on linkedIn 
Let move to programming examples:-

Using set() method to create set object.
1
2
3

set1 = set("this is python hunter")

print(set1)


We can pass list to built in set() method.
1

2
3

set1 = set(["this","is","python","python","hunter","list"])

print(set1)

Duplicate members in list will be removed.

Passing tuple to built in set() method.
1
2
3
4

set1 = set(("this","is","python","python","hunter","tuple"))

print(set1)



We can not add list as element.
1

set1 = set((["this","is","list"],["this","is","another list"]))



But we can  add tuple as element.

1
2

set1 = set((("this","is","list"),("this","is","another list")))

print(set1)



Set are mutable even the set carry immutable object.
1
2
3
4

set1 = set([1,2,4])

print(set1)

set1.add("this")

print(set1)



The above problem can be solved with frozenset method. Frozenset will not let the user to add any element or alter the set object.

1
2
3
4

set1 = frozenset([1,2,4])

print(set1)

set1.add("this")
print(set1)

it will give us exception
                                                                                         
AttributeError: 'frozenset' object has no attribute 'add' 
                                                                                           

Clearing set:-
1
2
3

set1 = {"this","is","python","hunter","simple","notation","for","set"}

print(set1)

set1.clear()



Copy Set:-
1
2
3
4
5
6

set1 = {"copy","set","elements"}

setCopy = set1

print(set1)

print(setCopy)

setCopy.clear()

print(set1)

setCopy is new var and pointing to original set1. both set1 and setCopy are pointing to same memory location so clearing either setObject will affect the other one. This is the concept of Shallow and Deep copy. Click here to learn more.


The above problem can be solved with copy method.
1
2
3
4
5
6
7

print("*"*20)

set1 = {"copy","set","elements"}

setCopy = set1.copy()

print(set1)

print(setCopy)

setCopy.clear()

print(set1)


in this case only the setCopy is cleared and set1 is no affected any more.


Take out the differece b/w two sets.
1
2
3
4

#Take out the differece b/w two sets

set1 = {'a','b','c','d','e'}

set2 = {'p','l','k','j','g'}

set3 = {'k','l','d','f','g'}



1


print(set1.difference(set2))

It will take out the elements which set1 has but set2 does not have.


1
2
3
4
5
6

print(set2.difference(set1))

# this can also be performed with '-' minus operator.

print(set1 - set2)

print(set2 - set1)

print((set1 - set2) - set3)

It will take out the elements which set2 has but set1 does not have.


difference_update()
1
2
3
4

set1 = {'a','b','c','d','e'}

set2 = {'b','c'}

set1.difference_update(set2)

print(set1)

In above example set2 is the sub set because it has all the elements that set1 has. set1.difference_update(set2) will remove the sub set ('b','c') from set1 and the resulting set will be the remaining elements e.g ('a','d','e').

The set1.difference_update(set2) is equvelent to set1 = set1 - set2. see the example below.

1
2
3
4

set1 = {'a','b','c','d','e'}

set2 = {'b','c'}

set1 = set1 - set2

print(set1)



discard()
The matching elements will be removed from set, if element is not in the set then nothing will happen.
1
2
3
4

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

set1.discard('a') # a will be removed.

print(set1)

set1.discard('h') # nothing  will be removed.




intersection()
The common elements will be returned.
1
2
3

set1 = {'a','b','c','d','e'}

set2 = {'b','c'}

print(set1.intersection(set2))# b and c will be returned


The set1.intersection(set2) is equvelent to set1 = set1 & set2. see the example below.
1
2
3
4

set1 = {'a','b','c','d','e'}

set2 = {'b','c'}

set1 = set1 & set2

print(set1)




subset()
Consider subset as child, this will help you understand the concept. (please read the comments in code for better understanding)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10

set1 = {'a','b','c','d','e'}

set2 = {'b','c'}

print(set1.issubset(set2))# false

print(set1 < set2) #false

print(set2.issubset(set1))# true, because the set2 is proper subset of set1 means that the set2 contains all the elements
                          # that set1 has.
print(set2 < set1) #true

print(set1 < set1) #false, always false, a set can never be a sub set of itself.

print(set1 <= set1)#true because of = sign.




superset()
Consider subset as parent, this will help you understand the concept. (please read the comments in code for better understanding)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10

set1 = {'a','b','c','d','e'}

set2 = {'b','c'}

print(set1.issuperset(set2))# true

print(set1 > set2) #true

print(set2.issuperset(set1))# false

print(set2 < set1) #true

print(set1 < set1) #false, always false, a set can never be a superset set of itself.

print(set1 <= set1)#true because of = sign.

print(set1.issuperset(set1))# will always give true.



pop() 
pop method will remove the element from starting of set.
1
2
3
4

x = {"a","b","c","d","e"}

print(x)

print(x.pop())

print(x.pop())


first the set will be sorted to acbde and then a and c will be pop out.



Comments

  1. Is it possible to add dictionary object as set element?

    ReplyDelete
    Replies
    1. No, it's not possible, as the dictionary object is mutable.

      Delete

Post a Comment

Thanks in anticipation.

Popular posts from this blog

XML, XSLT info by pran sukh on Python Hunter blog.

What is XML? Many computer systems contain data in incompatible formats. Exchanging data between incompatible systems (or upgraded systems) is a time-consuming task for web developers. Large amounts of data must be converted, and incompatible data is often lost. XML stores data in plain text format. This provides a software- and hardware-independent way of storing, transporting, and sharing data. XML also makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing data. With XML, data can be available to all kinds of "reading machines" like people, computers, voice machines, news feeds, etc. XML:- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category= "cooking" > <title lang= "en" > Every

Understanding the usage of underscore( _ ) of Python for beginner. On Python Hunter

Introduction: Just like you, a newbie in python scripting language, me too was confused about lot of new things in python that are not valid or available in other languages like Java, .Net etc. Just like other things i had seen the use of '_' underscore in python, at beginning level that flabbergasted me for a while.      With some research and practice i have summarised the following usage of '_' underscore in python. Hope you will find it helpful at beginning level. First Usage : Hold the previous output value. When used in interpreter. 1 2 3 4 5 6 7 _ = input () # For example you typed '5' print (_) # This will print '5' print ( int ( _ ) * int ( _ ) ) # This will print '25' print ( int ( _ ) + 10 ) The above will print '15', because last input was "5" and in above   line of code is producing '25' as output but not being handl

XSLT apply import tag by pran sukh on python hunter blog

Modular Programming is good attitude of best programmer. We often need to keep our code in modular approach so that is would be easy to maintain  and update or remove dead code and also it ease the process of bug tracking. XML and XSL  processors provide freedom to import multiple imports to process the same  XML  document. In the following  XML  data we have data from collage where student's and teacher's data is given. But we want to process the same  XML  data with different XSL files. Here in this example we want to show the teacher data in red background color and student data in green background color. Data.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "RootXSLT.xsl"?> <data> <DataFor name = "Student" id = "001" > <firstname>