简体   繁体   中英

Reversing list element in python

How to reverse list element one by one in python? I tried nested loop. But I couldn`t display second loop as "Result"

For example:

Input: 102 346 5897

Result: 201 643 7985

Assuming your input list consists of strings, you go like this:

> a = ['102','346','5897']
> for i in a:
>    print(i[::-1],end=' ')

returns 201 643 7985

You can use [::-1]

string='102 346 5897'
lst=string.split()[::-1]
print(' '.join(lst))

Try the following solution. you can use [::-1] to reverse a string.

x = ["123", "456", "789"]

y = []
for i in range(0,len(x)):
    y.append(x[i][::-1])
print(y)
['321', '654', '987']

You can use following trick with number inputs assuming inputs are numbers.

x = [123, 456, 789]
y = []
for i in range(0,len(x)):
    y.append(int(str(x[i])[::-1]))
print(y)
[321, 654, 987]

You can use the built in function 'reverse()' instead of for loop (more efficient code) :

code

def Reverse(lst):
   lst.reverse()
   return lst
  
lst = ["123", "456", "789"]
print(Reverse(lst))

output

['789', '456', '123']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM