Loading your page…
How to Reverse a String or List in Python (3 Methods)
Discover idiomatic Python techniques to reverse sequences, complete with time and space complexity trade-offs.
Published by Projet Carthage · Updated
Concepts & Theory
The slice `sequence[::-1]` creates a reversed copy of a string or list and leaves the original sequence unchanged.
The built-in `reversed()` function returns a lazy reverse iterator. It consumes O(1) auxiliary memory and is optimal when streaming values into a for loop.
For mutable lists, `list.reverse()` performs the inversion in place without allocating extra memory (O(1) space).
Code Example
Try this example# Méthode 1 : Slicing élégant (chaînes & listes)
texte = "Carthage"
inverse = texte[::-1]
print("Slicing :", inverse) # 'egahtraC'
# Méthode 2 : reversed() puis conversion en liste
mots = ["Python", "IA", "Code"]
print("Itérateur :", list(reversed(mots))) # ['Code', 'IA', 'Python']
# Méthode 3 : Inversion en place, sans copier la liste
nombres = [1, 2, 3, 4, 5]
nombres.reverse()
print("En place :", nombres) # [5, 4, 3, 2, 1]Common Pitfalls & Mistakes
Calling .reverse() on an immutable string
text = "hello"
text.reverse() # AttributeErrortext = "hello"
reversed_text = text[::-1]Strings are immutable in Python. The `.reverse()` method only exists on mutable list objects.
Frequently Asked Questions
Which method is fastest for reversing strings in Python?▾
Slicing is a concise option for producing a copy. Performance depends on your interpreter and data; benchmark your own inputs before choosing an optimisation.
Master Python with interactive exercises
Complete hands-on code challenges in your browser with real-time feedback and progressive hints.
