You can reverse a list with [::-1]
:
print(' '.join(O_string.split()[::-1]))
Output:
'Mr_T is name Me'
Here [::-1]
means take everything from the beginning to the end with a step size of minus one.
Alternatively, you can use the built-in function reversed
:
>>> ' '.join(reversed(O_string.split()))
'Mr_T is name Me'
About your algorithm. In my opinion it is always more difficult to think in negative indices. I would suggest to go positive:
O_string = ("Me name is Mr_T")
split_result = O_string.split()
res = []
x = len(split_result) - 1
while x >= 0:
res.append(split_result[x])
x = x-1
result=" ".join(res)
print (result)
Output:
'Mr_T is name Me'
Here:
x = len(split_result) - 1
gives you the last index of your list. We start indexing with 0
. So you need to subtract 1
from the length of the list.
You count it down with:
x = x-1
and stop as soon as you get a negative index:
while x >= 0:
Hint: Don't use list
as a variable name. It is a built-in and should better not be used for naming own objects. If you do, you cannot easily use list()
anymore (in the same namespace).