How to remove elements that are the same from a list

I have a list and I want to remove the dublicates(tiplicates) from this list.
My approach was:

  • sort the list

  • check if two adiacent items are the same, if so eliminate one of them.

inventory = ["twin bed", "twin bed", "headboard", "queen bed", "king bed", "dresser", "dresser", "table", "table", "nightstand", "nightstand", "king bed", "king bed", "twin bed", "twin bed", "sheets", "sheets", "pillow", "pillow_last"]
i = 0
for items in inventory:
  if inventory[i] == inventory[i+1]:
    inventory.pop(i)
    print(inventory,i)
    i -=1
  i +=1
print(inventory)

Looks like it will work but it will stop when i=9.
Can you please hel me understand why?

L.E:
Looks like

inventory.sort()
i = 0
for a in range(len(inventory)-1):
  if inventory[i] == inventory[i+1]:
    inventory.pop(i)
    print(inventory,i)
    i -=1
  i +=1
print(inventory)
print(len(inventory))

works better.

Hi,
In your first piece of code, you’re altering the thing you’re iterating over. This is usually a bad idea because it’s difficult to be certain where you are in the list at any one time.
I.e. first time round, items will be the value the element at index 0 “twin bed”.
Next time round, items will take the value at index 1. However, as you’ve popped an item, that will now be “headboard” and inventory is an element shorter.
So, i stops at 9 because your inventory list has been shrunk and the loop has run out of things to iterate through.

Hope that helps

2 Likes