Basic Operations
Part of the Logic & Flow section of Coddy's Python journey — lesson 30 of 78.
Sets come with built-in operations that allow you to perform common set-related tasks efficiently. These operations include adding elements, removing elements, and checking for the presence of elements.
Adding an element to a set:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
# Output: {1, 2, 3, 4}Note: add() modifies the set in place and returns None.
Removing an element from a set: (raises an error if it does not exist!)
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)
# Output: {1, 3}Checking for the presence of an element:
my_set = {1, 2, 3}
print(2 in my_set)
# Output: True
print(4 in my_set)
# Output: FalseChallenge
EasyCreate a function named manage_set that takes three arguments: set1 (a set), element_to_add, and element_to_remove. The function should perform the following operations:
- Add
element_to_addtoset1. - Attempt to remove
element_to_removefromset1. If the element is not in the set, do nothing. - Check if the number 5 is in
set1. If it is, return the string"5 is in the set". Otherwise, return the string"5 is not in the set".
Cheat sheet
Sets support several built-in operations for managing elements:
Adding an element:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
# Output: {1, 2, 3, 4}Removing an element: (raises an error if element doesn't exist)
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)
# Output: {1, 3}Checking for element presence:
my_set = {1, 2, 3}
print(2 in my_set)
# Output: True
print(4 in my_set)
# Output: FalseTry it yourself
def manage_set(set1, element_to_add, element_to_remove):
# Write code hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter