404 Brain Not Found
404 Brain Not Found

Reputation: 605

Python : Calling functions from inside another function parameter

I'm new to python so please excuse the layman description.

Question : Given a sentence, return a sentence with the words reversed

My Solution:

def sentence_reverse(text):
    a = text.split()
    a.reverse()
    return ' '.join(a)

Output:

sentence_reverse('I am home') --> 'home am I'
sentence_reverse('We are ready') --> 'ready are We'

the code works the way it is supposed to but my question is, why can't i make a function call directly from the returned result of the previous function. i,e

why can i not do something like

return ' '.join(text.split().reverse())

this would work just fine in java since i get List object from text.split() to which, i would operate on with the reverse() function which would return me the inverted list which would then be used by the join() to make this list into a string.

This, is also something that i have tried:

text.split() returns a List, and applying .reverse() function on it SHOULD return the elements of the same list in reverse order, but when i execute this line,print(text.split().reverse()), i get None

Upvotes: 1

Views: 176

Answers (3)

Rocky Li
Rocky Li

Reputation: 5958

Instead of using .reverse You can use python list iterator to reverse:

me = 'ready are We'
" ".join(me.split()[::-1])
>>> 'We are ready'

Upvotes: 2

UltraInstinct
UltraInstinct

Reputation: 44444

which would return me the inverted list ..

Here's the problem. In Python, calling list.reverse() doesn't return the reversed list. It just reverses it in place.

What you need is:

return " ".join(text.split()[::-1])

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71570

Because reverse returns None, and updates the list, so so None is not valid for join.

Yeah so reverse is inplace function so no way to fix that.

So Use reversed:

return ' '.join(reversed(text.split()))

Or [::-1]:

return ' '.join(text.split()[::-1])

From docs:

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. [1] This is a design principle for all mutable data structures in Python.


After code example.

https://docs.python.org/3/tutorial/datastructures.html

Upvotes: 4

Related Questions