8

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.

shrewmouse
  • 5,338
  • 3
  • 38
  • 43
dhana
  • 6,487
  • 4
  • 40
  • 63

5 Answers5

13

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
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 3
    +1 for `reversed( ... )` function. That is exactly what I needed to reverse only one part of my "multi-dimensional array" – Christopher Rucinski May 13 '18 at 18:37
  • It should be pointed out that the slicing notation will slice the list and return a new list, whereas the `reversed` function returns an iterator. I would prefer opting for the iterator in most cases. – CervEd Jun 03 '19 at 08:21
4

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"
freakish
  • 54,167
  • 9
  • 132
  • 169
3

Have you tried the following?

"".join(s for s in reversed(st))

reversed returns a reverse iterator. Documentation is here

msvalkon
  • 11,887
  • 2
  • 42
  • 38
0

Have you try this?

[x for x in a[::-1]]

[x for x in reversed(a)]

Both works fine, but it's more efficient using [::-1]

min(timeit.repeat(lambda: [x for x in a[::-1]]))

Out[144]: 0.7925415520003298

min(timeit.repeat(lambda: [x for x in reversed(a)]))

Out[145]: 0.854458618996432

Seba
  • 1
  • 2
0

This may be useful, similar to above answer but returns a list.

list_of_lists = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [1.0, 2.0, 3.0, 4.0]]
reversed_list = [("|||".join(reversed(list_item))).split('|||') for item in list_of_lists]
EddyWD
  • 197
  • 2
  • 15