Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return two list python?

Tags:

python

list

I am not sure how the return works in the following compare function? Why can it return the format like this?

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]
like image 704
umassjin Avatar asked Aug 01 '26 22:08

umassjin


2 Answers

It's not returning two lists. It's returning one of the 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's taking advantage of the fact that True in Python is treated as the value 1, and False is treated as the value 0, and using those as list indices.

like image 134
Amber Avatar answered Aug 03 '26 13:08

Amber


The boolean value of False is zero and the boolean value of True is one. They can both be used as indexes into 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 that makes it all clear :-)

like image 22
Raymond Hettinger Avatar answered Aug 03 '26 12:08

Raymond Hettinger