⬅ Previous Topic
Python TuplesNext Topic ⮕
Python Functions⬅ Previous Topic
Python TuplesNext Topic ⮕
Python FunctionsA Set in Python is a collection of items where:
You can create a set using curly braces {}
or the set()
function.
fruits = {"apple", "banana", "orange"}
print(fruits)
{'banana', 'orange', 'apple'}
Note: The order might look different when you run it. That’s okay — sets are unordered, so the order is not fixed.
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)
{1, 2, 3, 4, 5}
Why? Because sets automatically remove duplicates!
Let’s learn the basic operations on sets: Create, Read, Update, and Delete.
colors = {"red", "green", "blue"}
You can’t read by position, but you can check if something exists:
print("green" in colors) # True
print("yellow" in colors) # False
colors.add("yellow")
print(colors)
{'red', 'green', 'blue', 'yellow'}
You can use remove()
or discard()
:
colors.remove("green") # Removes green
colors.discard("pink") # Does nothing (pink not found)
print(colors)
{'red', 'blue', 'yellow'}
colors.clear()
print(colors)
set()
This means the set is now empty.
Sets are perfect when you want to keep only unique items and don’t care about the order. They are simple, fast, and super useful when removing duplicates or checking membership.
In the next topics, we’ll explore how sets can be compared and combined using set operations like union, intersection, and difference!
⬅ Previous Topic
Python TuplesNext Topic ⮕
Python FunctionsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.