How to reverse a list in Python

Reversing a list in Python is really, really easy.

This doesn’t apply only to list but to sequence in general (string and tuple for example).

msg = "hello there"
print(msg[::-1])
# ereht olleh 
my_tuple = (1, 2, 3)
print(my_tuple[::-1])
# (3, 2, 1) 

Enter fullscreen mode Exit fullscreen mode

The secret behind this magic? The slice object.

name = "christian"
print(name.__getitem__(slice(None, None, -1)))
# 'naitsirhc' 

Enter fullscreen mode Exit fullscreen mode

While old I really recommend reading the Python 2.3 What’s new, when the support for built-in types was introduced.

原文链接:How to reverse a list in Python

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容