Python sets

Share me please

Creating python sets 

[cc lang=”python”]
# creating simple set
s = { “cat”, “dog”, “bird” }
print(s)
print(type(s))

# creating set by special function set()
s = set( [ “horse”, “cat”, “cow” ] )
print(s)
print(type(s))
[/cc]

Standard operations with python sets

[cc lang=”python” height=”550px”]
# set of animals
set1 = { “cat”, “dog”, “bird” }
print(set1)

# second set of animals
set2 = { “cow” , “cat”, “horse”, “chicken” }
print(set2)

# make union (sum of two sets)
set3 = set1 | set2
print(set3)

# make difference between two sets
set3 = set1 – set2
print(set3)

# verify different order for difference of two sets
set3 = set2 – set1
print(set3)

# intersection = take these elements that are in both sets
set3 = set1 & set2
print(set3)

# symmetric difference = is the same as union with boths sets minus intersection
set3 = set1 ^ set2
print(set3)

set3 = (set1 | set2) – (set1 & set2)
print(set3)
[/cc]

Available functions with python sets

[cc lang=”python” height=”840px”]
# simple set of numbers
set1 = { 10, 20, 30, 40, 50 }
set2 = { 60, 70, 80, 90 }
# set is like list without defined order of elements
print(set1)
print(type(set1))

# adding new element to set
set1.add(60)
print(set1)

# add again the same element, can you ?
set1.add(60)
print(set1)

# use function for intersection
set3 = set1.intersection(set2)
print(set3)

# use function for difference
set3 = set1.difference(set2)
print(set1)
print(set2)
print(set3)

# make union of two sets
set3 = set1.union(set2)
print(set3)

# remove element 60 from set
set1.discard(60)
print(set1)

# copy existing set
set3 = set1.copy()
# clean set1 set
set1.clear()
# verify that copy is still the same
print(set1)
print(set3)

# remove element from the set
set2.pop()
print(set2)

# remove specified element from set
set2.remove(60)
print(set2)

[/cc]

Running sets with other data types in python

[cc lang=”python”]
# get difference between two lists using sets
list1 = [10,20,30,40]
list2 = [30,40,50,60]

# get the difference between two lists converted into sets
set1 = set(list1) – set(list2)

# convert set back to list
list1 = list(set1)

print(list1)
print(type(list1))
[/cc]