Exercise: Python

Questions for: Lists

How can you remove all occurrences of a specific element from a list in Python?
A:
list.remove_all(element)
B:
list.delete(element)
C:
list.remove(element, all=True)
D:
list = [x for x in list if x != element]
Answer: D
To remove all occurrences of a specific element, you can use a list comprehension to filter out the unwanted element.
What does the list.count() method return in Python?
A:
The total number of elements in the list.
B:
The number of occurrences of a specific element.
C:
The sum of all elements in the list.
D:
The index of the last occurrence of a specific element.
Answer: B
The count() method returns the number of occurrences of a specific element in a list.
What is the purpose of the list.reverse() method in Python?
A:
Sorts the list in ascending order.
B:
Reverses the order of elements in the list.
C:
Removes duplicate elements from the list.
D:
Appends the list to itself.
Answer: B
The reverse() method in Python lists is used to reverse the order of elements in-place.
How can you check if a list contains only numeric elements in Python?
A:
all(isinstance(x, int) for x in my_list)
B:
my_list.isnumeric()
C:
numeric(my_list)
D:
if my_list.has_numbers()
Answer: A
Using all() with isinstance() checks if all elements in the list are of type int.
What will the list.pop(2) method do?
A:
Removes the element at index 2.
B:
Removes the element with the value 2.
C:
Raises an error because index 2 does not exist.
D:
Removes all occurrences of the value 2.
Answer: A
The pop() method removes and returns the element at the specified index.
Ad Slot (Above Pagination)
Quiz