Set (set) is a very useful data structure. It behaves like a list, except that a set cannot contain duplicate values.
This is useful in many cases. For example, you might want to check if the list contains duplicate elements, you have two choices, and the first one needs to use a For loop, like this:
#use a For loop to check for duplicate elementsSome_list = ['a','b','C','b','D','m','N','N','b']dup= [] forValueinchsome_list:ifSome_list.count (value) >2: ifValue not inchdup:dup.append (value)PrintDup
Output Result:
C:\Python27\python.exe e:/python/testspider/fibon.py['b']
But there is a simpler and more elegant solution, which is to use the collection (sets), which you do directly:
#finding repeating elements using the Set functionSome_list = ['a','b','C','b','D','m','N','N','b']dup= Set ([x forXinchSome_listifSome_list.count (x) >2])Print(DUP)
Output:
C:\Python27\python.exe e:/python/testspider/fibon.pyset (['b'])
The Set function can also find the intersection in an element
#Set Lookup intersectionvalid = Set (['Yellow','Red','Blue','Green','Black']) Input_set= Set (['Red','Brown'])Print(input_set.intersection (valid))
Output
C:\Python27\python.exe e:/python/testspider/fibon.pyset (['red'])
Set function find two element difference set
#Set Lookup difference setvalid = Set (['Yellow','Red','Blue','Green','Black']) Input_set= Set (['Red','Brown'])Print(input_set.difference (valid))
Output:
C:\Python27\python.exe e:/python/testspider/fibon.pyset (['Brown'])
Python Advanced tutorial Set data structure