How do I reverse a list in Python?
Short answer
items[::-1] returns a reversed copy. items.reverse() reverses in place and returns None. reversed(items) returns a lazy iterator. Pick based on whether you want a copy.
items = ["a", "b", "c"]
items[::-1] # ['c', 'b', 'a'] — new list, original untouched
list(reversed(items)) # ['c', 'b', 'a'] — new list, via an iterator
items.reverse() # None — mutates items in place#Which one to use
items[::-1] when you want a copy and the list is small. It is the most readable and works on strings and tuples too.
reversed(items) when you are about to loop over it. It produces items one at a time instead of building a whole second list:
for item in reversed(items):
print(item)On a large list that is real memory saved.
items.reverse() when you genuinely want the original changed and do not need the old order.
#Reversing a string
Same slice:
"hello"[::-1] # 'olleh'There is no .reverse() on strings, because strings are immutable.