Sets
Set is an unordered collection whose values are not indexed and cannot be changed.
- Adding and removing items is allowed.
- Duplication is not allowed.
- Can be of any data type.
- Belong to class
set
.
True
and 1
are considered the same value. Same goes for False
and 0
.
Use len()
to get the length of set.
songs = {"Shame", "Walk", "stevie"}
print(len(songs)) # 3
Though you can’t access items using an index, you can use in
operator.
print("Walk" in songs) # True
print("Shame" not in songs) # False
We can add and remove items instead of changing items in set.
songs.add("Fake It")
print(songs) # {'Walk', 'stevie', 'Fake It', 'Shame'}
update()
adds items from one set to another.
new_songs = {"Good Grief", "Winter Of Our Youth"}
songs.update(new_songs)
print(songs)
"""
{'Shame', 'Walk', 'Good Grief', 'Winter Of Our Youth', 'stevie'}
"""
remove()
and discard()
lets you remove items from set.
songs.remove("Shame")
songs.discard("Walk")
print(songs) # {'stevie'}
pop()
removes a random items from the list.
x = songs.pop()
print(x) # Shame
print(songs) # {'Walk', 'stevie'}
union()
or update()
joins all items from two sets. You can also use |
operator.
songs = {"Shame", "Walk", "stevie"}
new_songs = {"Good Grief", "Send Them Off!", "Us Against the World"}
new = songs.union(new_songs)
print(new)
"""
{'Good Grief', 'Shame', 'Send Them Off!', 'Walk', 'Us Against the World', 'stevie'}
"""
new_new_songs = {"Mountain Sound", "Of The Night", "My Blood"}
new = songs | new_songs | new_new_songs
print(new)
"""
{'Mountain Sound', 'Good Grief', 'Walk', 'Of The Night', 'Shame', 'Us Against the World', 'Send Them Off!', 'My Blood', 'stevie'}
"""
intersection()
returns a set with items present in both the sets. You can also use &
operator.
ticket = {1, 2, 4, 5, 1}
new_ticket = {2, 45, 6, 1, 4}
new = ticket & new_ticket
print(new) # {1, 2, 4}
difference()
returns a set with items in first set not present in other set. You can also use -
operator.
new = ticket - new_ticket
old = new_ticket - ticket
print(new) # {5}
print(old) # {45, 6}
symmetric_difference()
keeps a set with elements not present in both the sets. You can also use ^
operator.
new = ticket ^ new_ticket
print(new) # {5, 6, 45}