240
笔下虽有千言,胸中实无一策

Python: How to reverse a list in python

If you don't mind overwriting the original and don't want to use slicing (as mentioned in comments), you can call reverse() method on the list.

>>> num_list = [1, 2, 3, 4, 5]

>>> num_list.reverse()

>>> num_list

[5, 4, 3, 2, 1]

 


If you want to loop over the reversed list, use the in built reversed() function, which returns an iterator (without creating a new list)

num_list = [1, 2, 3, 4, 5]
for num in reversed(num_list):
print num,
# prints 5 4 3 2 1

 

 

posted @ 2017-02-10 03:40  CasperWin  阅读(230)  评论(0编辑  收藏  举报