How to delete last item in list?

后端 未结 7 680
再見小時候
再見小時候 2021-01-30 06:08

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 calcula

相关标签:
7条回答
  • 2021-01-30 06:39

    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).

    0 讨论(0)
提交回复
热议问题