Sets and Type Convertions Flashcards
(32 cards)
What is the syntax for creating a set?
my_set = {1, 2, 3}
.
How to create an empty set?
Use set()
: my_set = set()
(not {}
, which creates a dictionary).
What is the key property of sets?
Sets store unique elements (no duplicates).
How to add an element to a set?
Use .add(item)
(e.g., my_set.add(4)
→ {1,2,3,4}
).
How to add multiple elements to a set?
Use .update()
: my_set.update([4,5])
→ {1,2,3,4,5}
.
How to remove an element from a set?
Use .remove(item)
(raises error if item is missing) or .discard(item)
(no error).
How to remove and return an arbitrary element from a set?
Use .pop()
(e.g., my_set.pop()
→ removes and returns an element).
How to clear all elements from a set?
Use .clear()
: my_set.clear()
→ set()
.
How to check if an element exists in a set?
Use in
: 2 in {1,2,3}
→ True
.
What is the union of two sets?
Use .union()
or |
: {1,2}.union({2,3})
→ {1,2,3}
.
What is the intersection of two sets?
Use .intersection()
or &
: {1,2}.intersection({2,3})
→ {2}
.
What is the difference between two sets?
Use .difference()
or -
: {1,2}.difference({2,3})
→ {1}
.
What is the symmetric difference between two sets?
Use .symmetric_difference()
or ^
: {1,2}.symmetric_difference({2,3})
→ {1,3}
.
How to check if one set is a subset of another?
Use .issubset()
: {1,2}.issubset({1,2,3})
→ True
.
How to check if one set is a superset of another?
Use .issuperset()
: {1,2,3}.issuperset({1,2})
→ True
.
How to create a set from a list?
Use set()
: set([1,2,2])
→ {1,2}
.
question
answer
How to convert a string to an integer?
Use int()
: int('5')
→ 5
.
How to convert a string to a float?
Use float()
: float('3.14')
→ 3.14
.
How to convert a number to a string?
Use str()
: str(10)
→ '10'
.
How to convert a list to a tuple?
Use tuple()
: tuple([1,2,3])
→ (1,2,3)
.
How to convert a tuple to a list?
Use list()
: list((1,2,3))
→ [1,2,3]
.
How to convert a list to a set?
Use set()
: set([1,2,2])
→ {1,2}
.
How to convert a set to a list?
Use list()
: list({1,2})
→ [1,2]
.