Reverse the content of each element in a list python
Question:
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 !
Answers:
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']
l=['123','456','789']
l1=[]
for i in l:
l1.append(int(i[::-1]))
print(l1)
Output:[321, 654, 987]
str1="I am a student from college"
str2=list(str1.split(" "))
print(str2)
reverse=[x[::-1]for x in str2 ]
print(reverse)
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 !
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']
l=['123','456','789']
l1=[]
for i in l:
l1.append(int(i[::-1]))
print(l1)
Output:[321, 654, 987]
str1="I am a student from college"
str2=list(str1.split(" "))
print(str2)
reverse=[x[::-1]for x in str2 ]
print(reverse)