Sets Flashcards

1
Q

Sets

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Insert single element

A

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}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Insert multiple elements in set

A
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}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Remove elements from set

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Set operations

A

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}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Set Comprehension

A

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}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly