How to Reverse a String or List using Python

Python comes with the power of slicing.

Let’s try it with a String:

>>> example1 = 'hello world' >>> example1[::-1] 'dlrow olleh'
Code language: Python (python)

Now let’s try the same with a List:

>>> example2 = ['h','e','l','l','o',' ','w','o','r','l','d'] >>> example2[::-1] ['d', 'l', 'r', 'o', 'w', ' ', 'o', 'l', 'l', 'e', 'h']
Code language: Python (python)

As we can see by passing in the third argument to our slice of -1, we are able to reverse the return value.

Another way we could do this is by manually looping through our list and swapping out indexed items.

Let’s try it with some code:

s = ["h","e","l","l","o"] # `s` is 5 items long # because we count from 0 in code, loop from 0-4 for i in range(0, len(s)-1): # only need to swap for the first half! # as the second half is already swapped! if i<len(s)/2: # perform our swap! s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i]
Code language: Python (python)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments