'Does anyone know what two brackets next to each other does in python (ex: [][],[][])

I was working on a recursion algorithm and needed some help, so I came here and did some digging. What I found works for what I wanted it to do (Link: python minmax using only recursion), but I don't understand why and how it works. Here is the code:

def minMax(A,n):
if A:
    header = A[0]
    tailend = A[1:]

    if tailend != []:
        minimum, maximum = minMax(tailend,n-1)
        return [header, minimum][minimum < header], [header, maximum][maximum > header]

    return header, header
return A

intlist = [30, 50, 20, 70, 10, 80, 25, 100, 60, 40]
print(minMax(intlist,len(intlist)))

What I dont understand is this piece: return [header, minimum][minimum < header], [header, maximum][maximum > header] How do the brackets work? As far as I know, brackets are used for slicing, lists, indexing, and the sort. But here, it appears that there are some sort of keywords going on from behind the scenes and I just can't figure it out. Any help would be appreciated.



Solution 1:[1]

Not an explanation, but a somewhat more Python (but still obtuse) way to write this as a one-liner is:

return header if minimum > header else minimum, header if maximum < header else maximum

which uses Python's variant of the ternary if-else expression.

To be more explicit, you could simply write

if minimum > header:
    a = header
else:
    a = minimum

if maximum < header:
    b = header
else:
    b = maximum

return (a, b)

or with the ternary expression:

a = header if minimum > header else minimum
b = header if maximum < header else maximum
return (a, b)

which in my opinion keeps the code reasonably short, while still being much clearer than the original.


Of course, the above is going all wrong about, but stays perhaps closer to the original statement. Here is what you (really) should do:

return min(minimum, header), max(maximum, header)

It shows the actual intent, and is far shorter than any other way of writing this. (It may ignore the actual purpose of the exercise, so it's a bit of out of context.)

Solution 2:[2]

[minimum < header] is the index for the list. Since indexes are supposed to be integers, [minimum < header] gets coerced to an integer. False goes to 0 and True goes to 1. So if minimum is less than header, minimum gets returned, because it is the element at index 1. Otherwise, header gets returned. This is a fancy way of getting min([header, minimum]). I'm not sure whether the person writing this was just showing off or forgot about min.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 9769953
Solution 2 Acccumulation