Python Sets

In Python, a Set is an unordered collection of items. To define a Set, you should enclose items within curly braces {}.

Each item in a Set is unique, there cannot be any duplicate element.

Because Set is an unordered collection, you cannot access elements in a list with index value.

DaysOfWeek = {"Monday", "Tuesday", "Wednesday", 
              "Thursday", "Friday", "Saturday", "Sunday"}

DaysOfWeek.add("Monday")

# DaysOfWeek : {"Monday", "Tuesday", "Wednesday", 
#               "Thursday", "Friday", "Saturday", "Sunday"}

# You cannot add an existing element to a Set,
# since it is not allowed to have duplicates in a Set.

You cannot access elements in a Set using an index. Following code gives:
TypeError : ‘set’ object is not subscriptable

print(DaysOfWeek[0])

Accessing Items in a Set

You cannot access items in s Set using an index value. However, you can access each value in iteration using a for loop.

DaysOfWeek = {"Monday", "Tuesday", "Wednesday",
              "Thursday", "Friday", "Saturday", "Sunday"}

for day in DaysOfWeek:
   print("Day is : " + day)

# Days are not printed in the order you created,
# because Set is an unordered collection.
# Day is : Thursday
# Day is : Wednesday
# Day is : Monday
# Day is : Saturday
# Day is : Tuesday
# Day is : Sunday
# Day is : Friday

Updating Items in a Set

You can only add items to a set or remove items from set. You cannot update existing items.

Adding Items

To add items to a set you can use either add() or update() method. The method add() is used to add a single item to a set, update() method is used to add multiple items to a set.

colors = {"Red", "Blue"}
# {"Red", "Blue"}

colors.add("Yellow")
# {"Red", "Blue", "Yellow"}

colors.update(["Green", "Orange"])
# {"Red", "Blue", "Yellow", "Green", "Orange"}

Removing Items

To remove an item from a set, you can use either discard() or remove() method. If the item you want to remove does not exist in the set, remove() method raises an error. However, discard() method does not raise an error if the item does not exist.

colors = {"Red", "Blue", "Yellow", "Green", "Orange"}

colors.discard("Red")
# {"Blue", "Yellow", "Green", "Orange"}

colors.remove("Blue")
# {"Yellow", "Green", "Orange"}

colors.discard("Magenta")
# {"Yellow", "Green", "Orange"}

KeyError: ‘Magenta’

colors.remove("Magenta")

# The set colors does not contain Magenta
# remove() method raises an error.

Filtering Duplicates in a List

Since sets cannot contain duplicates, you can use them to filter out duplicates in a list. To filter duplicates, convert your list to set, then convert it back to list.

colors = ["Red", "Blue", "Green", "Blue", "Green", "Red", "Yellow"]

colors = list(set(colors))
# ["Red", "Blue", "Green", "Yellow"]
SHARE