Here I am try to reverse the string using below logic,
st = "This is Ok"
rst = list(st)
rst.reverse()
''.join(s for s in rst)
It is working fine, But when I try to following below logic i am getting an error,
st = "This is Ok"
''.join(s for s in list(st).reverse())
Here is an error,
----> 1 ''.join(s for s in list(st).reverse())
TypeError: 'NoneType' object is not iterable
Please any one explain the above process.
list.reverse
is an inplace operation, so it will change the list and return None
. You should be using reversed
function, like this
"".join(reversed(rst))
I would personally recommend using slicing notation like this
rst[::-1]
For example,
rst = "cabbage"
print "".join(reversed(rst)) # egabbac
print rst[::-1] # egabbac
It fails because lst.reverse()
reverses a list in place and returns None
(and you cannot iterate over None
). What you are looking for is (for example) reversed(lst)
which creates a new list out of lst
which is reversed.
Note that if you want to reverse a string then you can do that directly (without lists):
>>> st = "This is Ok"
>>> st[::-1]
"kO si sihT"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With