s is a string and following code is giving me "None" while executing
n=list(s)
l = n.reverse()
print(l)
s is a string and following code is giving me "None" while executing
n=list(s)
l = n.reverse()
print(l)
You can use [::-1] for reverse.Slice notation is easy to reverse string
s = "reverse"
s = s[::-1]
print(s)
output
esrever
Problem:
reverse()
function is doing in place reversal of list and it is not returning anything that's the reason l
gets assigned None
As a solution after calling reverse()
print variable n
itself as shown
s = "abc"
n=list(s)
n.reverse()
print(n)
For your code, it should be
s='string'
n=list(s)
n.reverse()
print(''.join(n))
Output:
gnirts
You got to copy the list and then reverse it with l.reverse(), not l = n.reverse().
You have to use copy, not just l = n, because if you do so you will have two reference to the same data, so that when you reverse l you reverse also n. If you do not want to reverse also the original n list, you have to make a brand new copy with l = n. copy, then you reverse l, without modifying the original data stored with n label. You can copy a list also with l = n[:].
>>> s = "12345"
>>> n = list(s)
>>> l = n.copy() # or l = n[:]
>>> l.reverse()
>>> n
['1', '2', '3', '4', '5']
>>> l
['5', '4', '3', '2', '1']
>>>
If you want a string back
>>> k = "".join(l)
>>> k
'54321'
reverse() function returns None but reverse the list.
n=list(s)
l = n.reverse()
print(l)
print(n) #Reversed list
You can use reversed()
function as well.
l = list(reversed(n))
print(l)