my_set = {1, 2, 3} print(my_set) # {1, 2, 3}
set()
empty_set = set() print(empty_set) # set()
numbers = [1, 2, 3] numbers_set = set(numbers) print(numbers_set) # {1, 2, 3}
numbers = [1, 2, 3, 1, 4, 2] numbers_set = set(numbers) print(numbers_set) # {1, 2, 3, 4}
my_set = {1, "tere", [1, 2]}
TypeError: unhashable type: 'list'
None
add()
numbers = {1, 2, 3} numbers.add(4) print(numbers) # {1, 2, 3, 4} numbers.add(1) print(numbers) # {1, 2, 3, 4}
update()
numbers = {1, 2, 3} numbers.update([1, 2, 3, 4]) print(numbers) # {1, 2, 3, 4} numbers.update({1, 8}) print(numbers) # {1, 2, 3, 4, 8}
discard()
numbers = {1, 2, 3} numbers.discard(1) print(numbers) {2, 3} numbers.discard(6) # <- 6 does not exist, no error print(numbers) {2, 3}
remove()
numbers = {1, 2, 3} numbers.remove(1) print(numbers) # {2, 3} numbers.remove(6) # <- error
pop()
numbers = {4, 7, 1} one_number = numbers.pop() print(one_number) # 1 print(numbers) # {4, 7}
numbers = {4, 1, 6} for number in numbers: print(number)
1 4 6
a = {1, 2, 3} b = {3, 4, 5} print(a.union(b)) # {1, 2, 3, 4, 5} print(a | b) # {1, 2, 3, 4, 5}
a = {1, 2, 3} b = {2, 3, 4, 5} print(a.intersection(b)) # {2, 3} print(a & b) # {2, 3}
a = {1, 2, 3} b = {2, 3, 4, 5} print(a.difference(b)) # {1} print(a - b) # {1}
a = {1, 2, 3} b = {2, 3, 4, 5} print(a.symmetric_difference(b)) # {1, 4, 5} print(a ^ b) # {1, 4, 5}
len(my_set)
my_set = set("hello")
{'l', 'o', 'e', 'h'}
'h' in my_set
True
my_set = set("hello") print(len(my_set)) # 4 print('h' in my_set) # True print('u' in my_set) # False
names = ["john", "jane", "mary", "jane", "john", "smith", "monica"] print(f"There are {len(names)} names in the list") # There are 7 names in the list print(f"There are {len(set(names))} unique names in the list") # There are 5 unique names in the list