深度阅读

How to Reverse a List in Python

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

To reverse a list in Python, you can use the reverse() method or the slicing notation.

Using the reverse() method:

my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)  # Output: [5, 4, 3, 2, 1]

Using the slicing notation:

my_list = [1, 2, 3, 4, 5]
my_list = my_list[::-1]
print(my_list)  # Output: [5, 4, 3, 2, 1]

Both of these methods will reverse the order of the elements in the list.

Note that the reverse() method modifies the original list in place, whereas the slicing method creates a new reversed list.

相关标签

博客作者

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