Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python sets


empty_set = set()

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

# sets do not contain duplicates
print(basket)                      
# output {'orange', 'banana', 'pear', 'apple'}

# check if orange is in basket set
print('orange' in basket)
# output true

# convert a string to a set of letters - sets contains no duplicates
set_a = set('abcd')
set_b = set('bcde')

# the operations below returns new sets
# print letters in set_a but not in set_b - difference
print(set_a - set_b)
# output {'a'}

# print set letters that is in either set a or b - union
print(set_a | set_b)
# output {'a', 'c', 'e', 'b', 'd'}

# print letters that are in both set_a and set_b - intersection
print(set_a & set_b)
# output {'c', 'd', 'b'}

# print letters that are in set_a and set_b when the letters are found in a set but no the other set - symmetric_difference()
print(set_a ^ set_b)
# output {'a', 'e'}
Source by codefreelance.net #
 
PREVIOUS NEXT
Tagged: #python #sets
ADD COMMENT
Topic
Name
6+2 =