-3

I have a list:

lst = ['abcdef', 'uvwxyz']

I want to get as result:

['fedcba', 'zyxwvu']

How can I do that in Python 3 (and Python 2 if it's possible)?

EDIT :

Here i want to Reverse the content of each element in a list !

NOT Reverse the elements in the list !

If i do:

lst[::-1]

I'll get:

['uvwxyz', 'abcdef']

and that's not what i want !

Bilal
  • 2,296
  • 5
  • 32
  • 55
  • 3
    Have you done *any* research at all? – MattDMo Nov 10 '15 at 21:10
  • You can index a list or string with a negative step; Python 2 or 3 don't matter here, btw. –  Nov 10 '15 at 21:12
  • for `python-2.7` i edited my question, and yes i did some research of course, but i just find "Reversing `the elements` in the list", and i want to reverse the `content` of each element. – Bilal Nov 10 '15 at 21:13
  • @Evert, unless you wish to use `map` – John La Rooy Nov 10 '15 at 21:13
  • 3
    Possible duplicate of [Reverse a string in Python](http://stackoverflow.com/questions/931092/reverse-a-string-in-python) – letsc Nov 10 '15 at 21:14
  • 1
    so look up "*python reverse string*". I bet there's a result or 2 for that... – MattDMo Nov 10 '15 at 21:14

2 Answers2

6

The slice [::-1] means to use the entire list/string etc. and step through with a step of -1.

so:

>>> 'abcdef'[::-1]
'fedcba'

Since you need to do this for each item of a list, a list comprehension is a good solution

>>> lst = ['abcdef', 'uvwxyz']
>>> [x[::-1] for x in lst]
['fedcba', 'zyxwvu']
John La Rooy
  • 281,034
  • 50
  • 354
  • 495
0
l=['123','456','789']
l1=[]
for i in l:
    l1.append(int(i[::-1]))
print(l1)

Output:[321, 654, 987]

barbsan
  • 3,328
  • 11
  • 20
  • 28