2

In python, I have this list containing

['HELLO', 'WORLD']

how do I turn that list into

['OLLEH', 'DLROW'] 

4 Answers 4

9
>>> words = ['HELLO', 'WORLD']
>>> [word[::-1] for word in words]
['OLLEH', 'DLROW']
Sign up to request clarification or add additional context in comments.

1 Comment

@user2278906 You should check the mark next to his answer if you feel it helped you best.
3

Using a list comprehension:

reversed_list = [x[::-1] for x in old_list]

Comments

1

Arguably using the builtin reversed is more clear than slice notation x[::-1].

[reversed(word) for word in words]

or

map(reversed, words)

Map is fast without the lambda.

I just wish it was easier to get the string out of the resulting iterator. Is there anything better than ''.join() to put together the string from the iterator?

2 Comments

This isn't a full answer and no, there is nothing easier than having to use ''.join to put it together
[''.join(reversed(word)) for word in words] is the full version of your first solution, which is valid and some argue it is more readable than [::-1], but I am of the opinion that the reverse slice is much better
0

Using map and lambda(lambdas are slow):

>>> lis=['HELLO', 'WORLD']
>>> map(lambda x:x[::-1],lis)
['OLLEH', 'DLROW']

2 Comments

why the downvote? Is the answer not useful or incorrect anyhow?
map/lambda combo is unpythonic, and should not be recommended where a list comprehension is the one obvious way

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.