深度阅读

How to get the last element of list in Python

作者
作者
2023年08月22日
更新时间
8.22 分钟
阅读时间
0
阅读量

It looks like you may have accidentally included search results for a different question in your response. Nonetheless, here’s how you can get the last element of a list in Python:

To get the last element of a list in Python, you can use the index -1, which represents the last element of the list. For example:

my_list = [1, 2, 3, 4, 5]
last_element = my_list[-1]

print(last_element) # Output: 5

In this example, we define a list my_list and use the index -1 to get the last element of the list. We then store the result in the variable last_element and print it out to the console.

Note that this method assumes that the list is not empty. If you want to handle the case where the list is empty, you should check the length of the list before accessing the last element to avoid an IndexError.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。