Search⌘ K
AI Features

Sets

Explore the concept of sets in Python, learning their key properties like uniqueness and unordered elements. Understand how to create sets, perform mathematical operations, and manipulate set elements to handle collections without duplicates.

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:

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

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