-2

How can I delete the last value I appended to a list in python? For example, if a list is [1, 2, 3, 4, 5], I want to only delete the 5 but instead of saying list.remove(5) I want to say delete the last value I added to the list. This way I'll be able to delete the values according to the order, not what the actual value is.

I think I have to put whatever 'lastly appended value' in the parenthesis in list.remove(), but I don't know what to call the lastly appended value :(

  • Does this answer your question? [How do I get the last element of a list?](https://stackoverflow.com/questions/930397/how-do-i-get-the-last-element-of-a-list) – Jan_B Aug 04 '23 at 08:57
  • What are you trying to do by removing the last item? This looks like a [XY problem](https://en.wikipedia.org/wiki/XY_problem) and there might be a better solution. – mozway Aug 04 '23 at 08:59

2 Answers2

1

You can use,

list.pop()

to remove the last element.

Time Complexity: O(1) Auxiliary Space: O(1)

0

In fact, list.remove(5) is a bad way to do it -- what if 5 appears somewhere else in the list other than just the end.

One way is to use list.pop() which removes (and returns) the last element of a list

Another way is to use the del statement combined with the fact that you can use the -1 index to refer to the last element of a list:

>>> mylist = [1,7,9,3,5,7,5]
>>> del mylist[-1]
>>> print(mylist)
[1,7,9,3,5,7]

p.s. don't call your list list since that name is used by python...

Andrew Jaffe
  • 26,554
  • 4
  • 50
  • 59