Sunday, April 20, 2025

Python Sets

Sets are collections of unique elements. We don't care about positions here. That's why we will have different result every time sets are printed.

To create set, use curly bracket:


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

print(colors)
print(type(colors))

Result: 


{'Black', 'Yellow', 'Green', 'Red'}
<class 'set'>
>>> 

Or dedicated set() function. Don't forget to use double parentheses:


colors_2 = set(("White", "Blue"))

print(colors_2)
print(type(colors_2))

Result: 


{'Blue', 'White'}
<class 'set'>
>>> 

Try to print set multiple times - positions will be different every time:


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

print(colors)

Results: 


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

In next tutorial, we will learn how to Add or Update Sets with new elements.

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