Exercise: Python

Questions for: Sets

What is the result of the expression set([1, 2, 2, 3, 4, 4, 5])?
A:
{1, 2, 3, 4, 5}
B:
[1, 2, 3, 4, 5]
C:
set([1, 2, 3, 4, 5])
D:
({1, 2, 2, 3, 4, 4, 5})
Answer: A
A set automatically removes duplicate elements, resulting in {1, 2, 3, 4, 5}.
Which of the following methods is used to remove and return an arbitrary element from a set?
A:
set.remove(element)
B:
set.discard(element)
C:
set.pop()
D:
set.delete(element)
Answer: C
The pop() method removes and returns an arbitrary element from the set.
How do you create an empty set?
A:
empty_set = set()
B:
empty_set = {}
C:
empty_set = set([])
D:
empty_set = set('')
Answer: A
An empty set can be created using the set() constructor.
Which of the following statements about sets in Python is not correct?
A:
Elements within a set are unordered.
B:
Sets can contain duplicate elements.
C:
Sets can not be accessed using indices.
D:
Sets are mutable.
Answer: B
Sets in Python do not allow duplicate elements.
How can you find the intersection of two sets?
A:
set1.join(set2)
B:
set1 & set2
C:
set1.intersect(set2)
D:
set1.intersection(set2)
Answer: D
The intersection() method is used to find the common elements between two sets.
Ad Slot (Above Pagination)
Quiz