1

I am trying to remove the last item of a list/array even if there are duplicate items EG
list = ["h","e","l","l","o"," ","t","h","e","r,"e"]
It would remove the final "e" but not the second and ninth "e"

I have already tried
finalSentence.remove([finalSentence[len(finalSentence)-1]])
However this removes a random letter, I know this is because it is removing a letter rather than item number and python does not know which one to choose so it is a random one that is removed. But I do not know another way to get this to work

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
Jeff Kint
  • 27
  • 4
  • 2
    You should be using del to remove by index. https://stackoverflow.com/questions/11520492/difference-between-del-remove-and-pop-on-lists/11520540 – Deniablesummer Apr 13 '19 at 16:47

2 Answers2

2

.remove removes the first occurrence of an item. You could do something like

del my_list[len(my_list) - 1]

Or simply:

del my_list[-1]

Or, probably the most idiomatic:

my_list.pop()

Note, the above methods work in (amortized) constant time, and they modify my_list in-place.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
1

Do not use list as a variable name, as it will probably conflict with the built-in type. But try this:

mylist = mylist[:-1]

That uses a slice from the beginning of the list up to but not including the last element. If the list is empty, there is no apparent change. If you want an error to be raised, you should use one of the methods of @juanpa.arrivillaga.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50