How to delete last item in list?
I have this program that calculates the time taken to answer a specific question, and quits out of the while loop when answer is incorrect, but i want to delete the last calculation, so i can call min()
and it not be the wrong time, sorry if this is confusing.
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))
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).
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
list.pop()
removes and returns the last element of the list.
just simply use list.pop()
now if you want it the other way use : list.popleft()