Q:

python set methods

add()	#Adds an element to the set
clear()	#Removes all the elements from the set
copy()	#Returns a copy of the set
difference()  #Returns a set containing the difference between two or more sets
difference_update()	#Removes the items in this set that are also included in another, specified set
discard()	#Remove the specified item
intersection()	#Returns a set, that is the intersection of two other sets
intersection_update()	#Removes the items in this set that are not present in other, specified set(s)
isdisjoint()	#Returns whether two sets have a intersection or not
issubset()	#Returns whether another set contains this set or not
issuperset()	#Returns whether this set contains another set or not
pop()	#Removes an element from the set
remove()	#Removes the specified element
symmetric_difference()	#Returns a set with the symmetric differences of two sets
symmetric_difference_update()	#inserts the symmetric differences from this set and another
union()	#Return a set containing the union of sets
update()	#Update the set with the union of this set and others
7
# You can't create a set like this in Python
my_set = {} # ---- This is a Dictionary/Hashmap

# To create a empty set you have to use the built in method:
my_set = set() # Correct!


set_example = {1,3,2,5,3,6}
print(set_example)

# OUTPUT
# {1,3,2,5,6} ---- Sets do not contain duplicates and are unordered
13
set_example = {1, 2, 3, 4, 5, 5, 5}

print(set_example)

# OUTPUT
# {1, 2, 3, 4, 5} ----- Does not print repetitions
11
# Create a set
seta = {5,10,3,15,2,20}
# Or
setb = set([5, 10, 3, 15, 2, 20])

# Find the length use len()
print(len(setb))
2
set_of_base10_numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}
set_of_base2_numbers = {1, 0}

intersection = set_of_base10_numbers.intersection(set_of_base2_numbers)
union = set_of_base10_numbers.union(set_of_base2_numbers)

'''
intersection: {0, 1}:
	if the number is contained in both sets it becomes part of the intersection
union: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}:
	if the number exists in at lease one of the sets it becomes part of the union
'''
0

New to Communities?

Join the community