4 built-in data types
In Python, lists, sets, tuples, and dictionaries are used to store collections of data. Each has different properties and use cases.
- set: an unordered, mutable collection that does not allow duplicates.
It can contain different data types:
✅ (Integers, floats, strings, tuples (if the tuple only contains immutable types)
❌ not lists, dictionaries, sets (since they are mutable).
Use sets to store unique items and to perform mathematical set operations.
# a set can contain different data types as long as they are immutable
my_set = {1, "hello", 3.14, (1, 2, 3)}
# 'set' object is not subscriptable
print(my_set[1]) # error message
my_set = {1, 2, 3, 2, 1}
print(my_set) # {1, 2, 3} (duplicates removed)
# adding or removing elements
my_set.add(5) # {1, 2, 3, 5}
my_set.update([6, 7]) # {1, 2, 3, 5, 6, 7}
my_set.remove(7) # {1, 2, 3, 5, 6} (raises error if not found)
my_set.discard(10) # {1, 2, 3, 5, 6} (# No error if 10 is not found)
# set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.intersection_update(set2)
print(set1) # {1, 2}
set1.difference_update(set2)
print(set1) # {3}
print(set1 | set2) # Union → {1, 2, 3, 4, 5}
print(set1 & set2) # Intersection → {3}
print(set1 - set2) # Difference → {1, 2}
print(set1 ^ set2) # Symmetric Difference → {1, 2, 4, 5}
print(len(set1 & set2)) # 1
set1 = {1, 2, 3}
set2 = {1, 2}
set1 = {1, 2, 3}
set2 = {1, 2}
set3 = {3, 4, 5}
set4 = {4, 5}
set2.issubset(set1) # True
set1.issuperset(set2) # True
set3.issubset(set1) # False
set1.isdisjoint(set3) # False
set1.isdisjoint(set4) # True
# since sets are unordered, pop() removes a random element from the set
set1.pop()
# real world example
engineers = {'John', 'Jane', 'Jack', 'Janice'}
programmers = {'Jack', 'Sam', 'Susan', 'Janice'}
managers = {'Jane', 'Jack', 'Susan', 'Zack'}
# union
employees = engineers | programmers | managers
print(employees) # {'Sam', 'Jack', 'John', 'Zack', 'Susan', 'Janice', 'Jane'}
# intersection
engineering_management = engineers & managers
print(engineering_management) # {'Jack', 'Jane'}
# difference
fulltime_management = managers - engineers - programmers
print(fulltime_management) # {'Zack'}
employees.issuperset(engineers) # True
# add
engineers.add('Marvin') # {'John', 'Jack', 'Janice', 'Marvin', 'Jane'}
employees.update(engineers)
print(employees) # {'Sam', 'John', 'Jack', 'Zack', 'Susan', 'Janice', 'Marvin', 'Jane'}
for group in [engineers, programmers, managers, employees]:
group.discard('Susan') # remove element if present
if group == engineers:
print(f"engineers: {group}")
elif group == programmers:
print(f"programmers: {group}")
elif group == managers:
print(f"managers: {group}")
elif group == employees:
print(f"employees: {group}")
# engineers: {'Jack', 'John', 'Janice', 'Marvin', 'Jane'}
# programmers: {'Sam', 'Janice', 'Jack'}
# managers: {'Zack', 'Jack', 'Jane'}
# employees: {'Sam', 'John', 'Jack', 'Zack', 'Janice', 'Marvin', 'Jane'}