How to reverse a sublist in python

Viewed 43

Given the following list:

a = ['aux iyr','bac oxr','lmn xpn']

c = []
for i in a:
    x = i.split(" ")
    b= x[1][::-1] --- Got stuck after this line

Can anyone help me how to join it to the actual list and bring the expected output

output = ['aux ryi','bac rxo','lmn npx']

2 Answers

I believe you need two lines of codes, first splitting the values:

b = [x.split() for x in a]

Which returns:

[['aux', 'iyr'], ['bac', 'oxr'], ['lmn', 'xpn']]

And then reverting the order:

output = [x[0] +' '+ x[1][::-1] for x in b]

Which returns:

['aux ryi', 'bac rxo', 'lmn npx']

You can use the following simple comprehension:

[" ".join((x, y[::-1])) for x, y in map(str.split, a)]
# ['aux ryi', 'bac rxo', 'lmn npx']
Related