Python – Creating and Using Sets
Python sets are used to store multiple items in a single variable, and unlike a list, are unordered, unchangeable, and unindexed.
Python sets are used to store multiple items in a single variable, and unlike a list, are unordered, unchangeable, and unindexed.
A specific item cannot be accessed in a set by referring to an index or a key. To access items, a for loop or the in keyword can be used.
Once a Python set is created, you cannot change its items, but you can add new items using the add() method and update() method.
Once a Python set is created, you cannot change its items, but you can remove items using the remove(), discard(), pop(), and clear() methods, and the del keyword.
Python set items can be accessed by looping through them using a for loop.
Python sets can be joined (combined) using the union(), update(), intersection(), difference(), and symmetric_difference() methods.
The Python set difference() method returns a set that contains the difference between two sets.
The Python set difference_update() method removes the items that exist in both sets.
The Python set discard() method removes the specified item from the set.
The Python set intersection() method returns a set that contains only items that exist in both sets, or in all sets if more than two sets are compared.
The Python set intersection_update() method removes the items that are not present in both sets, or in all sets if more than two sets are compared.
The Python set isdisjoint() method returns True if none of the items are present in both sets, otherwise it returns False.
The Python set issubset() method returns True if all items in the set exists in the specified set, otherwise it returns False.
The Python set issuperset() method returns True if all items in the specified set exists in the original set, otherwise it returns False.
The Python set remove() method removes the specified element from the set.
The Python set symmetric_difference() method returns a set that contains all items from both sets, but not the items that are present in both sets.