How to use a set
Lesson 2 of 8 in Coddy's Register Login System Project course.
A set in Python is a collection that manages data similar to keys in dictionaries but without values.
To create a set:
new_set = set()A set can have only one item of the same kind.
For example, let's add an element to our new_set:
new_set.add(1)
print(new_set)
>>> {1}As of now, we have only 1 element, which is the integer 1
If we try to add another integer 1 to the set:
new_set.add(1)It won't affect the new_set because it already has this element.
After printing again the new_set:
print(new_set)
>>> {1}We get the same result.
To delete an item from a set use .remove(element):
new_set.remove(1)
print(new_set)
>>> set()Another important feature is the ability to check if an item is already in our set:
if 1 in new_set:
print("1 integer is in our new_set")
elif "1" in new_set:
print("1 string is in our new_set")
else:
print("no 1 is in our new_set")
>>> "1 integer is in our new_set"Challenge
EasyCreate a function named maintain_set that receives a set of integers, and an integer.
The function will check if the integer is in the set, if it is, it will return that integer multiplied by 2. If it is not in the set, it will insert it and return the set.
Try it yourself
def maintain_set(a_set, number):
# Your code here