How do I remove the last list item?

How can I delete the last item in a list in Python?

I’m working on a program that calculates the time taken to answer a specific question. The program quits the loop when the answer is incorrect, but I want to delete the last calculation so I can use min() to get the correct time, excluding the incorrect entry. Here’s my code:

from time import time

q = input('What do you want to type? ')
a = ' '
record = []
while a != '':
    start = time()
    a = input('Type: ')
    end = time()
    v = end - start
    record.append(v)
    if a == q:
        print('Time taken to type name: {:.2f}'.format(v))
    else:
        break
for i in record:
    print('{:.2f} seconds.'.format(i))

How can I remove the last element from the record list so that I can calculate the minimum time without including the incorrect answer? How can I achieve this using python list remove last element?

Hey All!

One simple way to remove the last element from a list is by using the pop() method. It removes and returns the last element. If you’re not interested in the value that’s being removed, you can just call it like this without storing the return value."

record.pop()

Yeah, that’s a good approach, @miro.vasil. Another method to do this is by using list slicing. You can slice the list to exclude the last element, which essentially creates a new list that contains all the items except the last one."

record = record[:-1]

Exactly, @panchal_archanaa! I like that method as well. Another alternative is to use the del statement. You can delete the last item by specifying the index -1, which refers to the last element in the list. It’s pretty straightforward."

del record[-1]