Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't list.reverse return a list?

Tags:

python

string

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.

like image 336
dhana Avatar asked Feb 20 '14 07:02

dhana


2 Answers

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
like image 165
thefourtheye Avatar answered Oct 14 '22 22:10

thefourtheye


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"
like image 45
freakish Avatar answered Oct 14 '22 23:10

freakish