Python Docs
Python Sets — Full Notes
A set is an unordered collection of unique items.
What is a Set?
myset = {"apple", "banana", "cherry"}thisset = {"apple", "banana", "cherry"}
print(thisset)Duplicate Values
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)thisset = {"apple", "banana", "cherry", True, 1, 2}
print(thisset)thisset = {"apple", "banana", "cherry", False, True, 0}
print(thisset)Length of a Set
thisset = {"apple", "banana", "cherry"}
print(len(thisset))Set Data Types
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}set1 = {"abc", 34, True, 40, "male"}thisset = set(("apple", "banana", "cherry"))
print(thisset)Access Items
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)thisset = {"apple", "banana", "cherry"}
print("banana" not in thisset)Add Items
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)thisset = {"apple", "banana", "cherry"}
mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)Remove Items
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)thisset = {"apple", "banana", "cherry"}
del thissetSet Methods
| Method | Description |
|---|---|
| add() | Adds an element to the set. |
| clear() | Removes all elements from the set. |
| copy() | Returns a shallow copy of the set. |
| difference() | Returns items present only in the first set. |
| difference_update() | Removes items found in another set. |
| discard() | Removes an item but does not give an error if missing. |
| intersection() | Returns items common to both sets. |
| intersection_update() | Removes items not present in all sets. |
| isdisjoint() | Returns True if sets have no common items. |
| issubset() | Returns True if all items exist in another set. |
| issuperset() | Returns True if this set contains all items of another set. |
| pop() | Removes a random item from the set. |
| remove() | Removes a specific item, error if missing. |
| symmetric_difference() | Returns items NOT common in both sets. |
| symmetric_difference_update() | Updates set with symmetric difference. |
| union() | Returns a new set with items from all sets. |
| update() | Adds items from other iterables to the set. |