Sunday, April 20, 2025

Python Sets, Add, Update

We can create sets with multiple same elements, but duplicates are disregarded in usage.

This is how to add new element to set - function add() will get the job done:


colors = {"Green", "Yellow", "Red", "Black", "Black"}
print(colors)

colors.add("Orange")
print(colors)

Result: 


{'Black', 'Red', 'Green', 'Yellow'}
{'Black', 'Yellow', 'Red', 'Orange', 'Green'}
>>> 

We can't use indexes here - you will get Traceback (Error):


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

print(colors[0])

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
Traceback (most recent call last):
  File "C:\Python38-64\ARCHIVE\learning-python.py", line 3, in <module>
    print(colors[0])
TypeError: 'set' object is not subscriptable
>>> 

We can't replace one element with another one using "string replace" approach. This will result in mess:


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

colors.update("Green", "OrangeRed")

print(colors)

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
{'e', 'd', 'Black', 'n', 'R', 'Yellow', 'Green', 'Red', 'r', 'g', 'a', 'O', 'G'}
>>> 

But we can add new things to sets with update() function with brackets inside parentheses:


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

colors.update(["OrangeRed"])

print(colors)

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
{'Green', 'OrangeRed', 'Red', 'Black', 'Yellow'}
>>> 

Sure, we can grab new elements using keyboard:


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

x = input("New Color for x: ")
y = input("New Color for y: ")

colors.update([x, y])

print(colors)

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
New Color for x: Magenta
New Color for y: Navy
{'Yellow', 'Black', 'Red', 'Green', 'Magenta', 'Navy'}
>>> 

Function len() will work here, just as with strings or tuples:


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

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

Result: 


============== RESTART: C:\Python38-64\ARCHIVE\learning-python.py ==============
Colors are:  {'Red', 'Black', 'Green', 'Yellow'}
Number of colors:  4
>>> 

In next tutorial, we will learn how Remove and Discard elements of sets.

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 .  ...