-2

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,883
  • 5
  • 37
  • 60
  • 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

3 Answers3

7

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
  • 295,403
  • 53
  • 369
  • 502
0
l=['123','456','789']
l1=[]
for i in l:
    l1.append(int(i[::-1]))
print(l1)

Output:[321, 654, 987]

barbsan
  • 3,418
  • 11
  • 21
  • 28
0
str1="I am a student from college"
str2=list(str1.split(" "))
print(str2)
reverse=[x[::-1]for x in str2 ]
print(reverse)
  • 1
    That looks like broken syntaxc, but more importantly it looks like no explanation whatsoever. If you add an explanation, I will happily help you with the correct formatting. – Yunnosch Jul 15 '22 at 12:57
  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 17 '22 at 09:15
  • 2
    This answer was reviewed in the [Low Quality Queue](https://stackoverflow.com/help/review-low-quality). Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Code only answers are **not considered good answers**, and are likely to be downvoted and/or deleted because they are **less useful** to a community of learners. It's only obvious to you. Explain what it does, and how it's different / **better** than existing answers. [From Review](https://stackoverflow.com/review/low-quality-posts/32476093) – Trenton McKinney Aug 13 '22 at 17:39