set(methods) Flashcards

(10 cards)

1
Q

A Python Set

A

An unordered collection of unique elements. It automatically removes duplicates.

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

How to create an empty set in Python

A

Use set() - not {} which creates a dictionary.

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

Method to add a single element to a set

A

.add(element)

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

Method to remove an element, which raises an error if the element isn’t there

A

.remove(element)

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

Method to remove an element, which does nothing if the element isn’t there (safer)

A

.discard(element)

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

Operation to find all elements in either of two sets (A or B)

A

Union (set1 | set2 or set1.union(set2))

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

Operation to find elements common to both of two sets (A and B)

A

Intersection (set1 & set2 or set1.intersection(set2))

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

Operation to find elements in the first set but not in the second (A minus B)

A

Difference (set1 - set2 or set1.difference(set2))

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

Operation to find elements in either set, but not in both (A XOR B)

A

Symmetric Difference (set1 ^ set2 or set1.symmetric_difference(set2))

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

What is the main advantage of using a set over a list for checking if an item exists?

A

Speed (membership testing is very fast, O(1), in sets)

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