Return two python lists?

I'm not sure how the return in the following comparison function works? Why can he return this format?

def func(self, num):
      num = sorted([str(x) for x in num], cmp=self.compare) 

def compare(self, a, b):
      return [1, -1][a + b > b + a]

      

+3


source to share


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


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







All Articles