SETS


  1. DIVE INTO THE SETS
  2. WORKING WITH SETS
  3. METHODS

1. DIVE INTO THE SETS

Unordered

Sets are unordered, which means that the items in a set are not stored in any particular order.The unordered nature of sets means that you cannot access the items in a set using indexing or slicing, and you cannot rely on the items being in a specific order when you iterate over the set.

Mutable

Sets are mutable, which means that you can add, modify, or remove items from a set after it is created.

No duplicate

Sets do not allow duplicates, which means that you cannot have multiple copies of the same item in a single set. When you add an item to a set, the set will only keep one copy of the item, even if you add the same item multiple times.

Syntax

Sets are defnied using curly braces {}

Utilizing sets

Sets are useful for storing and manipulating data because they allow you to quickly test if an item is present in the set, and they also allow you to easily eliminate duplicate entries. Sets also support some mathematical operations, such as union, intersection , difference... These operations can be useful for performing calculations and analyzing data.


2. WORKING WITH SETS

To create a set, enclose a sequence of items in curly braces {} :

countries={'Canada', 'Brazil', 'Japan'} # creates a set of strings
print(countries) # prints {'Brazil', 'Japan', 'Canada'}

or use the set function to create a set from a list :

listofcharacters=['Ron', 'Draco', 'Harry'] # a list
setofcharacters=set(listofcharacters) # creates a set from a list
print(setofcharacters) # prints {'Harry', 'Ron', 'Draco'}

or use the set function to create a set from a string. Each character in the string will be treated as a separate item in the set. As sets are unordered collections of unique items, so the order of the items may not be preserved when you create a set.

word='apple'
setofletters=set(word)
print(setofletters) #prints {'p', 'e', 'l', 'a'}

Python allows you to create a set from a sequence that contains duplicates, but it will only keep one unique instance of each duplicate item in the resulting set :

countries={'Canada', 'Canada', 'Brazil', 'Greece'}
print(countries) # prints {'Brazil', 'Canada', 'Greece'}

Sets can contain several types of objects, as long as they are immutable (i.e., they cannot be modified after they are created).Examples of immutable objects that can be stored in a set include integers, floats, strings, and tuples. Here's an example of creating a set that contains a mix of immutable objects:

mixedset={10,'hello',3.14, (1,2,3)} # sequence contains integer, string, float, tuple objects

Sets cannot contain mutable objects such as sets or dictionaries, because mutable objects can be modified after they are created, and this could potentially violate the uniqueness constraint of sets.

flavors=['chocolate', 'vanilla', 'strawberry'] # a list 
colors=['red', 'green', 'blue'] # another list
newset={flavors,colors} # returns TypeError: unhashable type: 'list'
cities1 = {"Cairo": "Egypt", "Nairobi": "Kenya"} # a dictionary
cities2 = {"Dakar": "Senegal", "Tripoli": "Libya"} # another dictionary
newset={cities1,cities2} #returns TypeError: unhashable type: 'dict'

An empty set can be created using the set functuon. using {} will result in an empty dictionary. When you print an empty set in Python, it will be displayed as set().

empty1=set()
print(type(empty1))  # prints <class 'set'> 
empty2={}
print(type(empty2)) # prints <class 'dict'>
print(empty1) # prints set()

You can use sets to perform common mathematical set operations, such as finding the minimum and maximum value, or the total sum of a set of numbers.

numbers = {1, 2, 3, 4, 5}    
print(min(numbers)) # prints 1 
print(max(numbers)) # prints 5
print(sum(numbers)) # prints 15

3. METHODS

A method is a function that is associated with a specific object or class and performs a specific task. The methods for working with sets can be categorized into the following groups:

These categories are not official and there are other ways to categorize the methods. The goal of these categories is to provide a helpful overview and a way to better understand and organize the many tools available.

REMOVING METHODS

clear(): removes all elements from the set. When you print an empty set in Python, it will be displayed as set().

planets = {'Venus', 'Mars', 'Jupiter'}
planets.clear()
print(planets) # returns set()

pop(): removes and returns an arbitrary element from the set. If the set is empty, it raises a KeyError exception.

cities = {'Madrid', 'Sydney', 'Oslo', 'Mexico'}
print(cities.pop()) # prints Madrid
print(cities) # prints {'Sydney', 'Mexico', 'Oslo'}

remove() : removes an element from the set. If the element is not present in the set, it raises a KeyError exception.

primes = {2,3,5,7,11,13,17,21}
primes.remove(2) 
print(primes)  # prints {3, 5, 7,11, 13, 17, 21}
primes.remove(4) # returns KeyError

discard() : removes an element from the set, if it is present. If the element is not present, it does nothing and it does not raise any error . discard() and remove() methods behave differently when the element being removed is not present in the set.

fruits = {'blueberry','orange', 'cherry', 'apple', 'banana'}
fruits.discard('cherry') 
print(fruits) # prints {'orange', 'apple', 'blueberry', 'banana'}
fruits.discard('kiwi')  
print(fruits) # prints {'orange', 'apple', 'blueberry', 'banana'}

COMBINATION METHODS

union(): returns the union of two sets as a new set. The union is defined as the set of elements that are present in either set. Sets union can also be performed using the | operator. The vertical line symbol | is often used as a union operator for sets in Python and other programming languages. It is also known as the "pipe" symbol.

# find the union of two sets with union() method
cities1 = {'Madrid', 'Sydney', 'Mexico'}
cities2 = {'New York', 'Chicago'}
print(cities1.union(cities2)) # prints {'New York', 'Mexico', 'Sydney', 'Chicago', 'Madrid'}
# union when an set element is in both sets 
cities3 = {'Madrid', 'Shanghai'} # 'Madrid' is in cities1 and cities2
print(cities1.union(cities3)) # {'Mexico', 'Sydney', 'Madrid', 'Shanghai'}

intersection(): returns the intersection of two sets as a new set. The intersection is defined as the set of elements that are present in both sets. Sets intersection can also be performed with the & operator

# find the intersection of two sets
colors={'orange','red', 'green'}
fruits = {'blueberry','orange','cherry','apple'}
print(colors.intersection(fruits)) # prints {'orange'}
print(colors & fruits) # prints {'orange'}

difference(): This method returns the difference between two sets as a new set. The difference is defined as the set of elements that are present in the first set, but not in the second set. You can also use the subtraction operator - to compute the difference between two sets difference() returns a set

numbers1 = {2,3,5,7}
numbers2 = {1,2,3}
print(numbers1.difference(numbers2))  # prints {5, 7}
print(numbers2.difference(numbers1)) # print {1}
print(numbers1-numbers2) # prints {5, 7}

difference_update(): updates the first set with the difference between it and the second set. The difference is defined as the set of elements that are present in the first set, but not in the second set.

primes = {2,3,5,7,11,13,17,21}
numbers = {2,4}
primes.difference_update(numbers)  
print(primes) # prints {3, 5, 7, 11, 13, 17, 21}

isdisjoint() : returns True if the two sets have no elements in common, and False otherwise.

cities = {'Madrid', 'Sydney', 'Oslo', 'Mexico'}
fruits = {'blueberry','orange','cherry','apple','banana'}
colors = {'blue','orange','green'}
print(cities.isdisjoint(fruits))  # prints True
print(fruits.isdisjoint(colors)) # prints False

issubset(): returns True if the first set is a subset of the second set, and False otherwise. Sets issubset can also be performed using the '<='' operator

numbers1 = {1,2,3}
numbers2 = {0,1,2,3,4,5}
print(numbers1.issubset(numbers2)) # prints True
print(numbers1<=numbers2) # prints True
numbers3 = {2,3,4,5}
print(numbers1.issubset(numbers3)) # prints False

intersection_update(): update a set with the intersection of itself and another set

numbers1 = {1,2,3,4,5}
numbers2 = {4,5,6,7,7}
numbers1.intersection_update(numbers2)  
print(numbers1) # prints {4, 5}

issuperset(): returns True if the first set is a superset of the second set, and False otherwise.

numbers1 = {1,2,3,4,5}
numbers2 = {2,3,4}
print(numbers1.issuperset(numbers2))  # prints True
numbers3={4,5,6}
print(numbers1.issuperset(numbers3))  # prints False

symmetric_difference():returns the symmetric difference between two sets as a new set. The symmetric difference is defined as the set of elements that are present in either set, but not in both sets. Sets symmetric difference can also be performed with the ^ operator

set1={1,2,3,4}
set2={4,5,6}
print(set1.symmetric_difference(set2)) # prints {1, 2, 3, 5, 6}
print(set1^set2) # prints {1, 2, 3, 5, 6}

symmetric_difference_update() : updates the first set with the symmetric difference between it and the second set. The symmetric difference is defined as the set of elements that are present in either set, but not in both sets.

set1={1,2,3,4}
set2={4,5,6}
set1.symmetric_difference_update(set2) 
print(set1) # prints {1, 2, 3, 5, 6}

update(): adds the elements from another set to the original set

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.update(y) 
print(x) # prints {'banana', 'microsoft', 'cherry', 'apple', 'google'}

ADDING METHOD

add() : adds an element to the set. If the element is already present in the set, it is ignored.

fruits = {'blueberry', 'orange', 'cherry'}
fruits.add('mango')
print(fruits)  # prints {'orange', 'mango', 'blueberry', 'cherry'}
fruits.add('blueberry') # 'blueberry' is already in set
print(fruits)  # prints {'orange', 'mango', 'blueberry', 'cherry'}

OTHER METHODS

copy() : returns a shallow copy of the set

composers = {'Vivaldi','Mozart','Bach'}
copy = composers.copy()  # {'Vivaldi','Mozart','Bach'}

len()returns the length of an object. It is not a method of the set data type specifically, but it can be used to find the number of key-value pairs in a dictionary.

set1={1,2,3,4}
print(len(set1)) # prints 4