Slice Trick `[::-1]`: Reverse Lists and Strings
Published:
• Last updated:
• By Jeferson Peter
Python
Reverse a list
nums = [1, 2, 3, 4, 5]
print(nums[::-1])
# [5, 4, 3, 2, 1]
Reverse a string
text = "Python"
print(text[::-1])
# nohtyP
Step slicing
nums = [0, 1, 2, 3, 4, 5, 6]
print(nums[::2]) # take every second
print(nums[::-2]) # reverse and take every second
# [0, 2, 4, 6]
# [6, 4, 2, 0]
Conclusion
The slice notation start:stop:step
is powerful.
With [::-1]
, you get a quick and Pythonic way to reverse any sequence.