Sets

You will learn about the set object in Python in this lesson.

Definition

A set is a collection of values that are not necessarily all the same type. To write a set, use braces around a comma-separated list. Take a look at a few examples using sets below:

Press + to interact
int_set = {1, 2, 3, 4, 5} # set having all integer values
print(int_set)
s = {10, "ten", "X"} # set having mixed data types
print(s)

Empty set

In Python, an empty set (one with no elements) cannot be written as {}. Instead, the set() function is used.

Press + to interact
emp_dict = {} # creating empty dictionary
emp_set = set() # creating empty set
# checking data types of both variables
print("Type of emp_dict:", type(emp_dict))
print("Type of emp_set:", type(emp_set))

Set properties

Sets have two important properties:

  • Sets have no duplicate elements. A value is either in the set, or it is not in the set. Sets provide the in and not in operators which allow us to check duplicates.
Press + to interact
s = {10, "ten", "X", "X"} # A set having mixed data type values
print(s) # this will give (10, "ten", "X") since sets have no duplicate elements
print("In:", 10 in s) # checking if 10 is present in s -> True
print("Not in:", "TEN" not in s) # checking if TEN is not present in s -> True
  • The order of elements in a set is unspecified, so you cannot index
...