np.array([e[::-1] for e in arr]) is the straight forward way of doing this, and is NOT bad numpy. or bypass numpy entirely with [e[::-1] for e in arr.tolist()]. You could also do something similar with np.vectorize or np.frompyfunc. These might scale a bit better.

'vectorize' in numpy means using compiled methods (and operators) to do the necessary iterations in compiled code. Those are nearly all numeric operations. For strings, numpy uses Python string methods. It does not have its own compiled string operations. Even the np.char functions use python string methods.

So there's no numpy equivalent to astr[::-1].

Some comparative times

In [16]: timeit np.array([s[::-1] for s in arr])
36.1 µs ± 151 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In [17]: timeit np.array([s[::-1] for s in arr.tolist()])
21.1 µs ± 76.5 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In [18]: timeit [s[::-1] for s in arr.tolist()]
8.29 µs ± 23.2 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

In [20]: timeit np.vectorize(lambda s: s[::-1])(arr)
65.9 µs ± 165 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In [21]: timeit np.frompyfunc(lambda s: s[::-1],1,1)(arr)
20.3 µs ± 76.5 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
Answer from hpaulj on Stack Overflow
Top answer
1 of 2
3

np.array([e[::-1] for e in arr]) is the straight forward way of doing this, and is NOT bad numpy. or bypass numpy entirely with [e[::-1] for e in arr.tolist()]. You could also do something similar with np.vectorize or np.frompyfunc. These might scale a bit better.

'vectorize' in numpy means using compiled methods (and operators) to do the necessary iterations in compiled code. Those are nearly all numeric operations. For strings, numpy uses Python string methods. It does not have its own compiled string operations. Even the np.char functions use python string methods.

So there's no numpy equivalent to astr[::-1].

Some comparative times

In [16]: timeit np.array([s[::-1] for s in arr])
36.1 µs ± 151 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In [17]: timeit np.array([s[::-1] for s in arr.tolist()])
21.1 µs ± 76.5 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In [18]: timeit [s[::-1] for s in arr.tolist()]
8.29 µs ± 23.2 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)

In [20]: timeit np.vectorize(lambda s: s[::-1])(arr)
65.9 µs ± 165 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

In [21]: timeit np.frompyfunc(lambda s: s[::-1],1,1)(arr)
20.3 µs ± 76.5 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
2 of 2
2

The following does the job by considering a different view of the original array. This means no additional arrays (and thus memory) are required. And no for loops :)

import numpy as np

A = np.array(['2', '3', '5', '7', '11', '13', '17', '19', '23', '29', '31', '37',
       '41', '43', '47', '53', '59', '61', '67', '71', '73', '79', '83',
       '89', '97'], dtype='<U2')

B = A.view(np.uint32)           # Interpret as individual numbers
B = B.reshape((A.shape[0],2))   # Group numbers in pairs
B[B[:,1] != 0, :] = B[B[:,1] != 0, ::-1] # Flip pairs if more than 1 digit

print(A) # ['2' '3' '5' '7' '11' '31' '71' '91' '32' '92' '13' '73' '14' '34' '74' '35' '95' '16' '76' '17' '37' '97' '38' '98' '79']

For short arrays, like the one you gave, @hpaulj's answer is faster. But for larger arrays, this method is faster. As an example, for an array of 100,000 elements, this method is approximately 5x faster compared to @hpaulj's fastest method ([s[::-1] for s in arr.tolist()]).

🌐
Reddit
reddit.com › r/learnpython › python: reversing array, list and string: problem with print
r/learnpython on Reddit: Python: Reversing Array, List and String: problem with print
August 23, 2023 -
import numpy as np
class PythonRevStrListArr:   
    def __init__(self, Str, List1, Arr):      
        self.Str = Str     
        self.List1 = List1      
        self.Arr = Arr   
    def ReverseList(self):      
        self.List1.reverse()      
        print("Lis1" + self.List1)   
    def ReverseString(self):      
        self.Str[::-1]      
        print("Str = "+self.Str)   
        def ReverseArray(self):      
        np.flip(self.Arr)      
        print("Arr = "+self.Arr)
if __name__ == "__main__":      
    List1 = [10, 20, 30, 40, 50]      
    Str1 = "5, 15, 25, 35"      
    arr = np.array([1, 11, 21, 31, 41, 51])      
    obj = PythonRevStrListArr(Str1, List1, arr)      
    obj.ReverseArray()      
    obj.ReverseString()      
    obj.ReverseList()

Hi,

I am getting following error message:

Traceback (most recent call last):  File "/home/zulfi/PycharmProjects/pythonProject2/main2.py", line 27, in <module>    
obj.ReverseArray()  
File "/home/zulfi/PycharmProjects/pythonProject2/main2.py", line 20, in ReverseArray      print("Arr = "+self.Arr)
numpy.core._exceptions.UFuncTypeError: ufunc 'add' did not contain a loop with signature matching types (dtype('<U21'), dtype('<U21')) -> dtype('<U21')

Somebody please guide me.

Zulfi.

Discussions

Quick Tip: Reversing a string in Python (in 1 line of code)
Your explanation for why the code works is about two-thirds incorrect. First off, there's no conversion to a "array" happening. Slices are part of the "sequence" protocol in Python and strings are sequences. While some sequences are implemented at a low level with arrays, others like range objects are not (the contents of a range are computed dynamically as they're needed). Many are quite a bit more complicated than a basic array, even if they do use an array for the main part of the data structure. Python's Unicode string type contains several pointers to arrays, one or two of which will contain the character data. Next, the meanings of missing slice elements is different depending on the direction of the slice (determined by the sign of the step term). For a forwards slice (with a positive step), the start and stop bounds default as you describe to 0 and len(the_sequence), respectively. But for a reverse slice like you're talking about here (with a negativestep), the start is -1 (or len(the_sequence)-1 if you prefer). The default for stop is notionally "before the start" of the sequence, but there's no actual numeric index that you can use since negative numbers count from the end of the list. Leaving out the stop part of the slice is the only way to make it work. I hope these clarifications don't seem too nit-picky. Python's a great language to learn programming with, and neat features like the "alien smiley" slice (really, look at it sideways! It's got four eyes) are one of the reasons. More on reddit.com
🌐 r/Python
1
0
January 13, 2021
How do I reverse a string in Python? - Stack Overflow
One rationale for excluding a string.reverse() method is to give python developers incentive to leverage the power of this special circumstance. In simplified terms, this simply means each individual character in a string can be easily operated on as a part of a sequential arrangement of elements, just like arrays ... More on stackoverflow.com
🌐 stackoverflow.com
linux - How to print string array in reverse order in python - Stack Overflow
Suppose that the string which I want to print it: 192.168.1.1 Then the output which I need is: 1.1.168.192 I use this command but it didn't help me: str = array[] str1 = str[::-1] print(str1) The More on stackoverflow.com
🌐 stackoverflow.com
Python: Reversing Array, List and String: problem with print
You can't use + to concatenate things that aren't strings. An array is not a string. Use an f-string instead. print(f"Arr = {self.Arr}") Same for your ReverseList method. More on reddit.com
🌐 r/learnpython
7
1
August 23, 2023
🌐
Python.org
discuss.python.org › ideas
Method for reversing strings - Ideas - Discussions on Python.org
February 20, 2025 - I would like to add a .reverse() method for strings. I think most modern languages have something like that and [::-1] is a bit archaic with little charm. There may be other methods like splitting the string, reversing the resulting list, and ...
🌐
AskPython
askpython.com › python › array › reverse-an-array-in-python
Reverse an Array in Python – 10 Examples - AskPython
April 14, 2026 - Original: [11, 22, 33, 44, 55] Reversed: [55, 44, 33, 22, 11] Original unchanged: [11, 22, 33, 44, 55] This is the most Pythonic one-liner. It works on any sequence (list, tuple, string).
🌐
Note.nkmk.me
note.nkmk.me › home › python
Reverse a List, String, Tuple in Python: reverse, reversed | note.nkmk.me
August 16, 2023 - In Python, you can reverse a list using the reverse() method, the built-in reversed() function, or slicing. To reverse a string (str) and a tuple, use reversed() or slicing. Reverse a list using the r ...
🌐
Medium
medium.com › @khasnobis.sanjit890 › python-reverse-string-74cc521cf8ca
Python Reverse String. Today we are going to write some code… | by Sanjit Khasnobis | Medium
September 10, 2023 - And it is going to traverse the whole string length. ... def reverseStr_loopinglist_appendmethod(inputStr): outputStrlist = [] inputStrlist = list(inputStr) len_of_list = len(inputStrlist) for i in range(len_of_list): outputStrlist.append(inputStrlist[(len_of_list-i)-1]) outputStr = "".join(outputStrlist) return outputStr
Find elsewhere
🌐
LeetCode
leetcode.com › problems › reverse-string
Reverse String - LeetCode
The input string is given as an array of characters s. You must do this by modifying the input array in-place [https://en.wikipedia.org/wiki/In-place_algorithm] with O(1) extra memory.
🌐
Medium
medium.com › geekculture › quick-tip-reversing-a-string-in-python-in-1-line-of-code-96e1c5324e1
Quick Tip: Reversing a String in Python (in 1 Line of Code) - Geek Culture - Medium
March 8, 2021 - This syntax reverses the string ... The syntax for the array slicing is as follows: [start:end:step] where empty start means 0 and empty stop means the length of the array....
🌐
Educative
educative.io › answers › how-do-you-reverse-a-string-in-python
How do you reverse a string in Python?
To start, let’s create a new array called reversedString[]. We can then loop over the list with iterating variable index initialized with the length of the list. In each iteration, concatenate value of str[index-1] with reverseString · Decrement ...
🌐
Reddit
reddit.com › r/python › quick tip: reversing a string in python (in 1 line of code)
r/Python on Reddit: Quick Tip: Reversing a string in Python (in 1 line of code)
January 13, 2021 -

You can easily reverse a string in python like this:

print("Hello"[::-1])

This syntax reverses the string by converting it to an array (in python strings are actually arrays of characters) and then slicing it The syntax for the array slicing is as follows: [start:end:step]
where empty start means 0 and empty stop means the length of the array. So [::-1] means to slice the array from the 1st element to the last element in reverse order.

Hope you enjoyed it!

Top answer
1 of 1
4
Your explanation for why the code works is about two-thirds incorrect. First off, there's no conversion to a "array" happening. Slices are part of the "sequence" protocol in Python and strings are sequences. While some sequences are implemented at a low level with arrays, others like range objects are not (the contents of a range are computed dynamically as they're needed). Many are quite a bit more complicated than a basic array, even if they do use an array for the main part of the data structure. Python's Unicode string type contains several pointers to arrays, one or two of which will contain the character data. Next, the meanings of missing slice elements is different depending on the direction of the slice (determined by the sign of the step term). For a forwards slice (with a positive step), the start and stop bounds default as you describe to 0 and len(the_sequence), respectively. But for a reverse slice like you're talking about here (with a negativestep), the start is -1 (or len(the_sequence)-1 if you prefer). The default for stop is notionally "before the start" of the sequence, but there's no actual numeric index that you can use since negative numbers count from the end of the list. Leaving out the stop part of the slice is the only way to make it work. I hope these clarifications don't seem too nit-picky. Python's a great language to learn programming with, and neat features like the "alien smiley" slice (really, look at it sideways! It's got four eyes) are one of the reasons.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-reverse-string
Python Reverse String - 5 Ways and the Best One | DigitalOcean
August 3, 2022 - I understand the first one is to tell Python to look at all the elements in string, the second one I’m unsure about but [ -1] means that the first item to return needs to be at length [-1]. What does the second colon operator tell Python to do? Thanks ... Hi, Thank you for the explanation. I also wanted to know how to add new lines to the output. For example I have made a reverse string input program: def reverse_slice(s): return s[::-1] s=input('enter a string ') print(s[::-1]) How would I a make my answer be on multiple lines?
🌐
Tutorialspoint
tutorialspoint.com › python › python_reverse_arrays.htm
Python - Reverse Arrays
There are various methods and approaches to reverse an array in Python including reverse() and reversed() methods. In Python, array is not one of the built-in data types. However, Python's standard library has array module which helps us to ...
Top answer
1 of 14
3168

Using slicing:

>>> 'hello world'[::-1]
'dlrow olleh'

Slice notation takes the form [start:stop:step]. In this case, we omit the start and stop positions since we want the whole string. We also use step = -1, which means, "repeatedly step from right to left by 1 character".

2 of 14
329

What is the best way of implementing a reverse function for strings?

My own experience with this question is academic. However, if you're a pro looking for the quick answer, use a slice that steps by -1:

>>> 'a string'[::-1]
'gnirts a'

or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join:

>>> ''.join(reversed('a string'))
'gnirts a'

or for readability and reusability, put the slice in a function

def reversed_string(a_string):
    return a_string[::-1]

and then:

>>> reversed_string('a_string')
'gnirts_a'

Longer explanation

If you're interested in the academic exposition, please keep reading.

There is no built-in reverse function in Python's str object.

Here is a couple of things about Python's strings you should know:

  1. In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.

  2. Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:

    string[subscript]
    

The subscript creates a slice by including a colon within the braces:

    string[start:stop:step]

To create a slice outside of the braces, you'll need to create a slice object:

    slice_obj = slice(start, stop, step)
    string[slice_obj]

A readable approach:

While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function, which can be rather relatively slow. Let's put this in a function - we'll come back to it:

def reverse_string_readable_answer(string):
    return ''.join(reversed(string))

Most performant approach:

Much faster is using a reverse slice:

'foo'[::-1]

But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let's create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.

start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
'foo'[reverse_slice]

Implement as Function

To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:

def reversed_string(a_string):
    return a_string[::-1]

And usage is simply:

reversed_string('foo')

What your teacher probably wants:

If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:

def reverse_a_string_slowly(a_string):
    new_string = ''
    index = len(a_string)
    while index:
        index -= 1                    # index = index - 1
        new_string += a_string[index] # new_string = new_string + character
    return new_string

This is theoretically bad because, remember, strings are immutable - so every time where it looks like you're appending a character onto your new_string, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.

Best Practice

Theoretically better is to collect your substrings in a list, and join them later:

def reverse_a_string_more_slowly(a_string):
    new_strings = []
    index = len(a_string)
    while index:
        index -= 1                       
        new_strings.append(a_string[index])
    return ''.join(new_strings)

However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.

Timings

Here are the timings:

>>> a_string = 'amanaplanacanalpanama' * 10
>>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
10.38789987564087
>>> min(timeit.repeat(lambda: reversed_string(a_string)))
0.6622700691223145
>>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
25.756799936294556
>>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
38.73570013046265

CPython optimizes string concatenation, whereas other implementations may not:

... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

🌐
Real Python
realpython.com › reverse-string-python
Reverse Strings in Python: reversed(), Slicing, and More – Real Python
July 31, 2023 - The first technique you’ll use to reverse a string involves a for loop and the concatenation operator (+). With two strings as operands, this operator returns a new string that results from joining the original ones.
🌐
dbader.org
dbader.org › blog › python-reverse-string
How to Reverse a String in Python – dbader.org
January 9, 2018 - An overview of the three main ways to reverse a Python string: “slicing”, reverse iteration, and the classic in-place reversal algorithm. Also includes performance benchmarks.
🌐
Interviewing.io
interviewing.io › questions › reverse-string
How to Reverse a String [Interview Question + Solution]
September 13, 2018 - Loop through each character of the original string. Push the character to the stack. Initialize an empty dynamic array reversed_string.
🌐
Medium
medium.com › @ryan_forrester_ › python-array-reverse-complete-guide-37f508724621
Python Array Reverse: Complete Guide | by ryan | Medium
October 28, 2024 - numbers = [1, 2, 3, 4, 5] reversed_numbers = numbers[::-1] print(reversed_numbers) # Output: [5, 4, 3, 2, 1] Breaking down the slice notation: - Empty start index (:) means begin from start - Empty end index (:) means go until the end - -1 step means move backwards · Here’s a practical example using slice notation with strings: