Python Sets
A Python set is a built-in data type that holds an unordered collection of unique items.
- purpose
- to perform operations like the mathematical set operations
- uses
- when the existence of an object in a collection is more important than the order or how many times it occurs
- allow for efficient membership tests
- created by:
- placing comma-separated sequence of items inside curly braces
{} - using the
set()function to create a set from another iterable
- placing comma-separated sequence of items inside curly braces
# Using curly braces
set1 = {'item1', 'item2', 'item3'}
# Using the set() function
set2 = set(['item1', 'item2', 'item3'])Determine Number of Items in a Set
The number of items in a Python set can be determined using the len() function.
set1 = {'item1', 'item2', 'item3'}
number_of_items = len(set1)set() Constructor
The set constructor set() is a built-in function for creating a set.
- takes an iterable as an argument
- returns a set containing unique elements of the iterable
- if no argument, creates an empty set
# Using a list as an argument
set1 = set(['item1', 'item2', 'item3', 'item1'])
# Using a string as an argument
set2 = set('hello')Accessing Items in a Set
- items cannot be accessed by index or key
- they are unordered
- can loop through a set
- can use the
inkeyword to determine if a value is in a set - once a set is created, items cannot be changed
- but new items can be added
set1 = {'item1', 'item2', 'item3'}
for item in set1:
print(item)Modify Sets
Add Items to a Set
To add an item to a Python set, use the add() method.
set1 = {'item1', 'item2', 'item3'}
set1.add('item4')To add multiple items to a set, use update() method.
set1 = {'item1', 'item2', 'item3'}
set1.update(['item4', 'item5'])Adding Sets
Use the update() method to add items from another set into the current set.
- takes one or more sets as arguments and adds all their elements to the current set
set1 = {'item1', 'item2', 'item3'}
set2 = {'item4', 'item5'}
set1.update(set2)Remove an Item From a Set
- To remove an item from a set:
remove()method- removes the specified item from the set, but if the item does not exist, it raises an error
discard()method- removes the specified item from the set, but it does not raise an error if the item does not exist
# Using remove() method
set1 = {'item1', 'item2', 'item3'}
set1.remove('item1')
# Using discard() method
set1 = {'item1', 'item2', 'item3'}
set1.discard('item1')Emptying a Set
The clear() method is used to empty a set.
set1 = {'item1', 'item2', 'item3'}
set1.clear()Deleting a Set
Delete a set using the del keyword.
- removes the entire set from memory
- attempting to use the set afterward will result in a
NameError
# Creating a set
network_devices = {'Router1', 'Switch1', 'Firewall1'}
# Using del to delete the set
del network_devices