Exercise: Lists

Questions for: Lists

How can you create a list containing only the unique elements from another list in Python?
A:
list.distinct()
B:
list.unique()
C:
list(set(list))
D:
list.remove_duplicates()
Answer: C
Converting a list to a set removes duplicates, and then converting it back to a list creates a new list with unique elements.
How can you find the frequency of each element in a list in Python?
A:
list.count(element)
B:
list.frequency(element)
C:
dict(Counter(list))
D:
list.freq(element)
Answer: C
Using Counter and dict() can create a dictionary with element frequencies.
What will the list.extend([7, 8, 9]) method do?
A:
Adds a single element [7, 8, 9] to the list.
B:
Adds individual elements 7, 8, 9 to the end of the list.
C:
Merges the list with [7, 8, 9] creating a new list.
D:
Inserts [7, 8, 9] at the beginning of the list.
Answer: B
The extend() method adds individual elements from the iterable to the end of the list.
How can you reverse the order of elements in a list without modifying the original list?
A:
reversed_list = list.reverse()
B:
reversed_list = list[::-1]
C:
reversed_list = list.reverse_copy()
D:
reversed_list = list.reverse(True)
Answer: B
Using slicing [::-1] creates a new list with the reversed order of elements.
What does the list.remove(42) method do in Python?
A:
Removes the element with the value 42.
B:
Removes the first occurrence of 42.
C:
Raises an error if the element 42 is not found.
D:
Removes all occurrences of 42.
Answer: B
The remove() method in Python lists removes the first occurrence of a specific element.
Ad Slot (Above Pagination)
Quiz