Python Lesson 14: Sets in Python

  1. Create a Set
  2. Loop Through a Set
  3. Add a item to a Set
  4. Remove an item from a Set
  5. Set Operations: Combine 2 Sets. Keep only unique values
  6. Set Operations: Combine 2 Sets and keep only common values
  7. Set Operations: Combine 2 Sets and remove items in the first list that are present in the second list

Features of a Set

A set is a collection of objects. It contains the following features:

  • It is unordered
  • The items in the set are unchangeable but the set is changeable
  • It is unindexed
  • Doesn’t allow duplicates

1) Create a Set

#Create a Set
workdays = {"Monday","Tuesday","Wednesday","Thursday","Friday"}
print(workdays)
Notebook Output

2) Loop Through a Set

Use a for loop to loop through a set.

workdays = {"Monday","Tuesday","Wednesday","Thursday","Friday"}
for x in workdays:
    print(x)
Notebook Output

3) Add a item to a Set

Use the add method to add an item to a set.

workdays = {"Monday","Tuesday","Wednesday","Thursday","Friday"}
for x in workdays:
    print(x)
Notebook Output

4) Remove an item from a Set

To remove an item from a Set use the remove() method

workdays = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
workdays.remove("Saturday")
print(workdays)
Notebook Output

5) Set Operations: Combine 2 Sets. Keep only unique values

Use the “|” operator to combine 2 sets and keep only unique values

#Combine 2 sets. Keep only unique values
workdays = {"Monday","Tuesday","Wednesday","Thursday"}
workdays2 = {"Wednesday","Thursday","Friday"}
allworkdays = workdays|workdays2
print(allworkdays)
Notebook Output

6) Set Operations: Combine 2 Sets and keep only common values

Use the “&” operator to combine 2 sets and keep only common values.

#Combine 2 sets. Keep only common values
workdays = {"Monday","Tuesday","Wednesday","Thursday"}
workdays2 = {"Wednesday","Thursday","Friday"}
allworkdays = workdays&workdays2
print(allworkdays)
Notebook Output

7) Set Operations: Combine 2 Sets and remove items in the first list that are present in the second list

Use the “-” operator to combine 2 Sets and remove items in the first list that are present in the second list

#Remove items in the first list that are present in the second list
workdays = {"Monday","Tuesday","Wednesday","Thursday"}
workdays2 = {"Wednesday","Thursday","Friday"}
allworkdays = workdays - workdays2
print(allworkdays)
Notebook Output

Recommended Books