Sets Flashcards

1
Q

Definition of a set

A

A set is a unique collection of objects in Python. You can denote a set with a curly bracket {}. Python will automatically remove duplicate items:

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

Convert list to set will remove duplicate items

A

album_list = [“Michael Jackson”, “Thriller”, 1982, “00:42:19”, \
“Pop, Rock, R&B”, 46.0, 65, “30-Nov-82”, None, 10.0]
album_set = set(album_list)
album_set

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

Add an element using add()

A

A.add(“NSYNC”)
A
{‘AC/DC’, ‘Back in Black’, ‘NSYNC’, ‘Thriller’}

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

Remove an element

A

A.remove(“NSYNC”)

A

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

We can verify if an element is in the set using the in command:

A

“AC/DC” in A

True

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

Find intersection of 2 sets

A

You can find the intersect of two sets as follow using &:
intersection = album_set1 & album_set2
intersection
{‘AC/DC’, ‘Back in Black’}

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

You can find all the elements that are only contained in album_set1 using the difference method:

A

album_set1.difference(album_set2)

{‘Thriller’}

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

The elements in album_set2 but not in album_set1 is given by:

A

album_set2.difference(album_set1)

{‘The Dark Side of the Moon’}

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

Union of 2 albums

A

album_set1.union(album_set2)

{‘AC/DC’, ‘Back in Black’, ‘The Dark Side of the Moon’, ‘Thriller’}

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

And you can check if a set is a superset or subset of another set, respectively, like this:

A

set(album_set1).issuperset(album_set2)

False

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