Sets Flashcards
Sets
Sets are initialized using curly braces {} or set() in python.
Unordered collection of unique values
list1 = [1,2,3,4,3,2,4] set1 = set(list1) set1 {1, 2, 3, 4}
it will automatically remove duplicate values from the set.
Insert single element
We can insert a single element into a set using the add function of sets.
~~~
s = {1, 2, 3, 3, 2, 4, 5, 5}
s.add(6)
~~~
{1, 2, 3, 4, 5, 6}
Insert multiple elements in set
s = {1, 2, 3, 3, 2, 4, 5, 5} s.update([6, 7, 8]) print(s)
Output:
{1, 2, 3, 4, 5, 6, 7, 8}
Remove elements from set
s = {1, 2, 3, 3, 2, 4, 5, 5}
print(s)
s.remove(4) #raises error if element is not in set
print(s)
s.discard(1) #doesnot raise error
print(s)
Set operations
a = {1, 2, 3, 3, 2, 4, 5, 5}
b = {4, 6, 7, 9, 3}
All the unique elements in both the sets.
Performs the Intersection of 2 sets
print(a & b)
{3, 4}
All the elements common to both the sets.
Performs the Union of 2 sets
print(a | b)
{1, 2, 3, 4, 5, 6, 7, 9}
The elements that are unique to the first set
Performs the Difference of 2 sets
print(a - b)
{1, 2, 5}
All the elements not common to both the sets.
Performs the Symmetric Difference of
print(a ^ b)
{1, 2, 5, 6, 7, 9}
Set Comprehension
Set Comprehension:
It is a shorter syntax to create a new set using values of an existing set.
a = [0, 1, 2, 3]
b will store values which are 1 greater than the values stored in a
~~~
b = [i + 1 for i in a]
print(b)
~~~
Output:
[1, 2, 3, 4]
a = {0, 1, 2, 3}
b will store squares of the elements of a
~~~
b = {i ** 2 for i in a}
print(b)
~~~
Output:
{0, 1, 4, 9}