gtrix
gtrix

Reputation: 3

(Python) How do I reverse characters of a list item

I want to reverse character order of every item in a list

I have myList = ['78', '79', '7a'] and I want it to get the output 87 97 a7

so far I've tried:

newList = [x[::-1] for x in myList][::-1]

and

def reverseWord(word):
    return word[::-1]

myList = ['78', '79', '7a']

newList = [reverseWord(word) for word in myList]

this would either return the original list or reverse the entire list and not just the items

Upvotes: 0

Views: 246

Answers (3)

belamy
belamy

Reputation: 76

Well, a one-liner to do the job :

newList = list(map(lambda x:''.join(reversed(x)), myList))
['87', '97', 'a7']

Upvotes: 0

Hamzah Zabin
Hamzah Zabin

Reputation: 93

Since your trying to reverse only the items inside the list and not the list it-self you only need to remove the extra [::-1],so your code should look like this:

myList = ['78', '79', '7a']
newList = [x[::-1] for x in myList]

In addition your second code using the reverseWord method is correct and gives you exactly the output you wanted.

def reverseWord(word):
return word[::-1]

myList = ['78', '79', '7a']

newList = [reverseWord(word) for word in myList]

Upvotes: 0

azro
azro

Reputation: 54148

In your line [x[::-1] for x in myList][::-1], the final [::-1] does reverse the list, you don't need it

What you missing is only formatting : join the element using a space

myList = ['78', '79', '7a']
res = " ".join(x[::-1] for x in myList)
print(res)  # 87 97 a7

Upvotes: 1

Related Questions