Sunday, April 20, 2025

Python Sets, Remove, Discard

To remove element from set use remove() function:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))
print("-" * 50)

colors.remove("Yellow")
print("After: ", colors)
print("Number of colors: ", len(colors))

Result:

Colors are:  {'Green', 'Black', 'Yellow', 'Red'}
Number of colors:  4
--------------------------------------------------
After:  {'Green', 'Black', 'Red'}
Number of colors:  3
>>> 

Error on multiple Remove Operations:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))
print("-" * 50)

colors.remove("Yellow")
colors.remove("Yellow")
colors.remove("Yellow")

print("After: ", colors)
print("Number of colors: ", len(colors))

Result: 


Colors are:  {'Yellow', 'Green', 'Black', 'Red'}
Number of colors:  4
--------------------------------------------------
Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 8, in <module>
    colors.remove("Yellow")
KeyError: 'Yellow'
>>> 

But we can use discard() function to evade errors:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))
print("-" * 50)

colors.discard("Yellow")
colors.discard("Yellow")
colors.discard("Yellow")

print("After: ", colors)
print("Number of colors: ", len(colors))

Result:

Colors are:  {'Green', 'Red', 'Yellow', 'Black'}
Number of colors:  4
--------------------------------------------------
After:  {'Green', 'Red', 'Black'}
Number of colors:  3
>>> 

Function clear() will remove all elements:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)
print("Number of colors: ", len(colors))
print("-" * 50)

colors.clear()

print("After: ", colors)
print("Number of colors: ", len(colors))

Result: 


Colors are:  {'Black', 'Red', 'Green', 'Yellow'}
Number of colors:  4
--------------------------------------------------
After:  set()
Number of colors:  0
>>> 

To destroy set, use del() function:


colors = {"Green", "Yellow", "Red", "Black", "Black"}

print("Colors are: ", colors)

del colors

print(colors)

We can't use something we destroyed:


Colors are:  {'Green', 'Red', 'Black', 'Yellow'}
Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 7, in <module>
    print(colors)
NameError: name 'colors' is not defined
>>> 

Next tutorial will be about Dictionaries.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...