How to delete last item in list?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Meditation
--
Chapters
00:00 How To Delete Last Item In List?
00:27 Answer 1 Score 15
00:46 Accepted Answer Score 437
01:42 Answer 3 Score 189
01:59 Answer 4 Score 160
02:07 Thank you
--
Full question
https://stackoverflow.com/questions/1816...
--
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.