Python Lesson 14: Sets in Python

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)

```

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)

```

3) Add a item to a Set

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

```

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)

```

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)

```

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&amp;workdays2
print(allworkdays)

```

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)

```