Reputation: 6525
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.
Upvotes: 8
Views: 8081
Reputation: 317
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]
Upvotes: 0
Reputation: 1
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
Upvotes: 0
Reputation: 12077
Have you tried the following?
"".join(s for s in reversed(st))
reversed
returns a reverse iterator. Documentation is here
Upvotes: 3
Reputation: 239473
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
Upvotes: 13
Reputation: 56467
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"
Upvotes: 4