0

I have a list where each element is a letter. Like this:

myList = ['L', 'H', 'V', 'M']

However, I want to reverse these letters and store them as a string. Like this:

myString = 'MVHL'

is there an easy way to do this in python? is there a .reverse I could call on my list and then just loop through and add items to my string?

1
  • 1
    Search "Python how to reverse a list" and "Python how to convert a list to a string" Commented Nov 25, 2013 at 19:33

2 Answers 2

8

There is a reversed() function, as well as the [::-1] negative-stride slice:

>>> myList = ['L', 'H', 'V', 'M']
>>> ''.join(reversed(myList))
'MVHL'
>>> ''.join(myList[::-1])
'MVHL'

Both get the job done admirably when combined with the str.join() method, but of the two, the negative stride slice is the faster method:

>>> import timeit
>>> timeit.timeit("''.join(reversed(myList))", 'from __main__ import myList')
1.4639930725097656
>>> timeit.timeit("''.join(myList[::-1])", 'from __main__ import myList')
0.4923250675201416

This is because str.join() really wants a list, to pass over the strings in the input list twice (once for allocating space, the second time for copying the character data), and a negative slice returns a list directly, while reversed() returns an iterator instead.

Sign up to request clarification or add additional context in comments.

Comments

5

You can use reversed (or [::-1]) and str.join:

>>> myList = ['L', 'H', 'V', 'M']
>>> "".join(reversed(myList))
'MVHL'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.