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

 

原文地址:https://www.cnblogs.com/casperwin/p/6384824.html