I'm trying to remove all Strings that are of even length in a set. Here is my code so far, but I am having trouble getting the index from the iterator in the enhanced-for-loop.
public static void removeEvenLength(Set<String> list) {
for (String s : list) {
if (s.length() % 2 == 0) {
list.remove(s);
}
}
}
Python Set remove() MethodThe remove() method removes the specified element from the set. This method is different from the discard() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.
The built-in method, discard() in Python, removes the element from the set only if the element is present in the set. If the element is not present in the set, then no error or exception is raised and the original set is printed.
Deleting a single element from the set container is very simple in C++. The idea is to pass the given element to the set::erase function, which erases it from the set.
Given a set, the task is to write a Python program remove multiple elements from set. Example: Input : test_set = {6, 4, 2, 7, 9}, rem_ele = [2, 4, 8] Output : {9, 6, 7} Explanation : 2, 4 are removed from set.
A Set
has no concept of an index of an element. The elements have no order in the set. Moreover, you should use an Iterator
when iterating to avoid a ConcurrentModificationException
when removing an element from a collection while looping over it:
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String s = iterator.next();
if (s.length() % 2 == 0) {
iterator.remove();
}
}
Note the call to Iterator.remove()
instead of Set.remove()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With