How to Reverse a String or List using Python

0 min read 149 words

Python comes with the power of slicing.

Let’s try it with a String:

>>> example1 = 'hello world'

>>> example1[::-1]

'dlrow olleh'

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']

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]
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags