How to delete last item in list?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle3
--
Chapters
00:00 Question
00:39 Accepted answer (Score 391)
01:45 Answer 2 (Score 182)
02:07 Answer 3 (Score 146)
02:20 Answer 4 (Score 11)
02:37 Thank you
--
Full question
https://stackoverflow.com/questions/1816...
Accepted answer links:
[Code Like a Pythonista: Idiomatic Python]: http://web.archive.org/web/2017031613125...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #time #python3x
#avk47
ACCEPTED ANSWER
Score 437
If I understood the question correctly, you can use the slicing notation to keep everything except the last item:
record = record[:-1]
But a better way is to delete the item directly:
del record[-1]
Note 1: Note that using record = record[:-1] does not really remove the last element, but assign the sublist to record. This makes a difference if you run it inside a function and record is a parameter. With record = record[:-1] the original list (outside the function) is unchanged, with del record[-1] or record.pop() the list is changed. (as stated by @pltrdy in the comments)
Note 2: The code could use some Python idioms. I highly recommend reading this:
Code Like a Pythonista: Idiomatic Python (via wayback machine archive).
ANSWER 2
Score 189
you should use this
del record[-1]
The problem with
record = record[:-1]
Is that it makes a copy of the list every time you remove an item, so isn't very efficient
ANSWER 3
Score 160
list.pop() removes and returns the last element of the list.
ANSWER 4
Score 15
You need:
record = record[:-1]
before the for loop.
This will set record to the current record list but without the last item. You may, depending on your needs, want to ensure the list isn't empty before doing this.