-1

s is a string and following code is giving me "None" while executing

n=list(s)
l = n.reverse()
print(l)
Muku
  • 538
  • 4
  • 18
  • 1
    there is no problem with your code check if your string 's' is None – Prakash Palnati Nov 30 '17 at 05:26
  • the reversed string is stored in n. – sanket mokashi Nov 30 '17 at 05:39
  • It's conventional in Python for functions & methods which mutate their argument in-place to return `None`. – PM 2Ring Nov 30 '17 at 05:58
  • Here we can do the same as you could read in my previous comments. You need to edit your this question to make it **very clear** that it is not a duplicate, **but without making the already posted answers invalid**. I am not sure if it can be done, but if yes, do the same (edit it, click "reopen", ping me in a comment and I cast another reopen vote). – peterh Jan 16 '21 at 21:29

7 Answers7

1

Try this:

n=list(s)
n.reverse()
print(n)
waqasgard
  • 801
  • 7
  • 25
0

You can use [::-1] for reverse.Slice notation is easy to reverse string

s = "reverse"
s  = s[::-1]
print(s)

output

esrever 
sachin dubey
  • 755
  • 9
  • 28
0

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)
Mahesh Karia
  • 2,045
  • 1
  • 12
  • 23
0

For your code, it should be

s='string'
n=list(s)
n.reverse()
print(''.join(n))

Output:

gnirts
Sumit S Chawla
  • 3,180
  • 1
  • 14
  • 33
0

reverse

You got to copy the list and then reverse it with l.reverse(), not l = n.reverse().

copy

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']
>>>

Thake a list and get the items in a string

If you want a string back

>>> k = "".join(l)
>>> k
'54321'
PythonProgrammi
  • 22,305
  • 3
  • 41
  • 34
-1

reverse() function returns None but reverse the list.

n=list(s)
l = n.reverse()
print(l)
print(n) #Reversed list
Mr. Sigma.
  • 405
  • 1
  • 4
  • 15
-1

You can use reversed() function as well.

l = list(reversed(n))
print(l)