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
Sorry, I’m not entirely sure what you mean, but here think of it this way:
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:
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:
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:
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 asx[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’.