📘 Lesson  ·  Lesson 79

Reverse String or List

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)                  # nohtyP

Expected 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.

Reverse a String or List in Python

Python में slicing या built-in functions से string या list reverse करना बहुत आसान है।

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)                  # nohtyP

Expected Output

nohtyP [5, 4, 3, 2, 1] [5, 4, 3, 2, 1] nohtyP

कैसे काम करता है

  • [::-1] slicing reverse करने का सबसे छोटा तरीका है।
  • reversed() भी काम करता है; या loop में reversed string बनाएं।

सारांश

  • Python में slicing या built-in functions से string या list reverse करना बहुत आसान है।
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n