Getting the last element of a list

后端 未结 12 1419
一向
一向 2020-11-22 04:58

In Python, how do you get the last element of a list?

12条回答
  •  萌比男神i
    2020-11-22 05:54

    list[-1] will retrieve the last element of the list without changing the list. list.pop() will retrieve the last element of the list, but it will mutate/change the original list. Usually, mutating the original list is not recommended.

    Alternatively, if, for some reason, you're looking for something less pythonic, you could use list[len(list)-1], assuming the list is not empty.

提交回复
热议问题