My list consists on several items:
["book","rule","eraser","clipboard","pencil",etc]
Let say I have an element ["book"] and I want to match with another element ["rule"] with the same len (4). then I want to remove both elements from the list.
["eraser","clipboard","pencil",etc]
I tried using a for loop and zip(lists, lists[1:]) but I can only remove the elements next to each other while other elements (like papers and pencil, len = 6) are never removed.
I want to remove same length words and have a final list with only the words whose length has no match or found no pair. For example:
["book","rule","eraser","clipboard","pencil","book"]
then the final list will be:
["clipboard","book"]
as book and clipboard found no pair.
>Solution :
You can try:
from collections import Counter
lst = ["book", "rule", "eraser", "clipboard", "pencil", "book"]
c = {k: v % 2 for k, v in Counter(map(len, lst)).items()}
out = []
for v in reversed(lst):
if c[len(v)] == 1:
out.append(v)
c[len(v)] -= 1
print(out[::-1])
Prints:
['clipboard', 'book']