Set is a collection of elements that don't allow duplicate value. An item can be added multiple times in a list but can't do that in a set.
Python set operations. Add item to set, Update an item, remove items. Sets add(), update(), remove(), discard() functions.
unique_numbers = {"one", "tow", "three"}
unique_numbers = set(("one", "tow", "three"))
print(unique_numbers)
unique_numbers = {"one", "tow", "three"}
len(unique_numbers)
unique_numbers = {"one", "two", "three", "four", "five"}
print( 'four' in unique_numbers )
unique_numbers = set(("one", "tow", "three"))
for number in unique_numbers:
print(number)
unique_numbers = {"one", "tow", "three"}
unique_numbers.add("fout")
print(unique_numbers)
Output:
{'three', 'fout', 'one', 'tow'}
unique_numbers = {"one", "tow", "three"}
others = {"fout", "file"}
unique_numbers.update(others)
print(unique_numbers)
Output:
{'file', 'fout', 'one', 'three', 'tow'}
unique_numbers = {"one", "tow", "three", "four", "five"}
unique_numbers.remove("three")
print(unique_numbers)
Output:
{'one', 'four', 'tow', 'five'}
unique_numbers = {"one", "tow", "three", "four", "five"}
unique_numbers.remove("three")
print(unique_numbers)
Output:
{'one', 'four', 'tow', 'five'}
The pop() method remove item randomly because the set is not an ordered collection.
unique_numbers = {"one", "tow", "three", "four", "five"}
unique_numbers.pop()
print(unique_numbers)
unique_numbers = {"one", "tow", "three", "four", "five"}
unique_numbers.clear()
print(unique_numbers)
unique_numbers = {"one", "tow", "three", "four", "five"}
del unique_numbers
A = {'orange', 'banana', 'pear', 'apple', 'apple'}
print(type(A))
print(A)
A.add("where")
print(A)
A.update('banana', 'Mango')
print(A)
A.remove("where")
print(A)
A.discard("where")
print(A)
B = set('apple')
print(type(B))
print(B)
Output:
{'banana', 'apple', 'pear', 'orange'}
{'apple', 'where', 'banana', 'orange', 'pear'}
{'o', 'apple', 'a', 'where', 'b', 'banana', 'M', 'g', 'orange', 'n', 'pear'}
{'o', 'apple', 'a', 'b', 'banana', 'M', 'g', 'orange', 'n', 'pear'}
{'o', 'apple', 'a', 'b', 'banana', 'M', 'g', 'orange', 'n', 'pear'}
{'p', 'a', 'e', 'l'}