📘 Lesson · Lesson 79
Reverse String or List
Reverse a String or List in Python
Python makes it very easy to reverse a string or list using slicing or built-in functions.
Python Program
Python
text = "Python"
print(text[::-1]) # nohtyP
nums = [1, 2, 3, 4, 5]
print(nums[::-1]) # [5, 4, 3, 2, 1]
print(list(reversed(nums))) # [5, 4, 3, 2, 1]
# Reverse without slicing
rev = ""
for ch in text:
rev = ch + rev
print(rev) # nohtyPExpected Output
nohtyP
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
nohtyP
How it Works
[::-1]slicing is the shortest way to reverse.reversed()also works; or build a reversed string in a loop.
Summary
- Python makes it very easy to reverse a string or list using slicing or built-in functions.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.