Return two python lists?
2 answers
It doesn't return two lists. It returns one of two values ββfrom the first list. Consider this rewriting:
def compare(self, a, b):
possible_results = [1, -1]
return possible_results[a + b > b + a]
It takes advantage of the fact that True
in Python it treats a value 1
, but False
treats it as a value 0
and uses them as indexes of a list.
+6
source to share
Boolean False is zero, and Boolean True is one. They can be used as indices on a list:
# Normal indexing with integers
>>> ['guido', 'barry'][0]
'guido'
>>> ['guido', 'barry'][1]
'barry'
# Indexing with booleans
>>> ['guido', 'barry'][False]
'guido'
>>> ['guido', 'barry'][True]
'barry'
# Indexing with the boolean result of a test
>>> ['guido', 'barry'][5 > 10]
'guido'
>>> ['guido', 'barry'][5 < 10]
'barry'
Hope everything is clear :-)
+3
source to share