Example 1: python sets
# 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
Example 2: sets in python
The simplest way to create set is:
1. from list
code:
s = [1,2,3]
set = set(s)
print(set)
2. s,add() method
code:
set.add(1)
set.add(2)
set.remove(2)
print(set)
3. Set conatins unique elements
Example 3: python set
# A set contains unique elements of which the order is not important
s = set()
s.add(1)
s.add(2)
s.remove(1)
print(s)
# Can also be created from a list (or some other data structures)
num_list = [1,2,3]
set_from_list = set(num_list)
Example 4: sets in python
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # show that duplicates have been removed
# OUTPUT {'orange', 'banana', 'pear', 'apple'}
print('orange' in basket) # fast membership testing
# OUTPUT True
print('crabgrass' in basket)
# OUTPUT False
# Demonstrate set operations on unique letters from two words
print(a = set('abracadabra'))
print(b = set('alacazam'))
print(a) # unique letters in a
# OUTPUT {'a', 'r', 'b', 'c', 'd'}
print(a - b) # letters in a but not in b
# OUTPUT {'r', 'd', 'b'}
print(a | b) # letters in a or b or both
# OUTPUT {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
print(a & b) # letters in both a and b
# OUTPUT {'a', 'c'}
print(a ^ b) # letters in a or b but not both
# OUTPUT {'r', 'd', 'b', 'm', 'z', 'l'}
Example 5: get length of set python
# 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))
Example 6: python set
set_example = {1, 2, 3, 4, 5, 5, 5}
print(set_example)
# OUTPUT
# {1, 2, 3, 4, 5} ----- Does not print repetitions