In Python 3, all division yields a float quotient.
>>> 6 / 2
When we see a lot of repetition in the code it becomes evident that abstracting away that code makes everything a lot clearer.
if ___ % 2:
return (lst[___] + lst[___]) / 2
Above we can see the gist of the function with repeated elements removed. Note that
len(lst) is repeated five times in your code. We can abstract away that expression by assigning its output to a variable.
n = len(lst)
Run once, use the result multiple times. Notice also how many times your code divides by 2? That operation can also be abstracted away.
m = n / 2
As we know that will produce a float quotient but we can cast that to an integer with the
m = int(n / 2)
For odd length lists
m will be the middle index.
[ ] [ ] [ ] [m] [ ] [ ] [ ]
For an even length list
m will be the lowest index in the upper half of the list.
lower half upper half
[ ] [ ] [ ] [ ] [m] [ ] [ ] [ ]
That means the other middle element in the pair is at index
m - 1.
[ ] [ ] [ ] [m-1] [m] [ ] [ ] [ ]
This is enough information for us to fill in the blanks in our model…
if n % 2:
return lst[ m ]
return (lst[ m - 1 ] + lst[ m ]) / 2 # will be a float
When we plan ahead, the work gets lighter and mistakes are reduced to a minimum.