Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

about the return expression

level: beginner

the following code will print 'False'

def function(x):
    if len(x) == 5: return True
    else: return x[0] == x[-1]

print function('annb')

why does the line "else: return x[0] == x[-1]" print False? i do understand what's happening but i'm having difficulties to put this into plain english...how can this behaviour be described?

is this a commonly / often used "technique"?

I first came across this particular syntax when trying to solve a palindrome exercise recursivley. It seems that the only way to make recursion work is to use this shorthand approach:

def isPalindrome(s):
 if len(s) <= 1: return True
 else: return s[0] == s[-1] and isPalindrome(s[1:-1])

print isPalindrome('anna')

thanks Baba


1 Answers

Sorry, I'm not entirely sure what you mean, but here think of it this way:

return (x[0] == x[-1])

If you only consider what is within the parenthesis, you realize that, that 'statement' equates to a boolean, right? That's why you can also do:

if x[0] == x[-1]

So basically, what is being returned here is a boolean that says whether or not x[0] is equal to [-1].

One could be more explicit and expand this statement to something like this:

if x[0] == x[-1]: # if this is true
    return True # then return true
else:
    return False

But as you can see, both the condition and what you would like to return are the same value, so one just does it shorthand like you saw:

return x[0] == x[-1]

Sorry if I misunderstood your question.

EDIT: If you referred to the negative index (x[-1]), in Python, negative indices basically 'wrap around', so where as x[0] would be the first element from 'left-to-right' so to speak, x[-1] loops around such that it is the first element from 'right-to-left'.

like image 103
Jorge Israel Peña Avatar answered Mar 18 '26 02:03

Jorge Israel Peña