-1

I have this function:

def median(numbers):
    middle = int(len(numbers)/2)
    return numbers[middle]

print(median([4, 5, 6, 7, 8]))

The writing style of this line is a bit confusing for me:

return numbers[middle]

If I am not mistaken it returns the input numbers' order in a list.
Is there a different way to read this line?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Fayzulla
  • 89
  • 1
  • 8

3 Answers3

1

numbers[middle] is slicing of the list, which returns the element at middle position. It returns a single element, which is at the middle index, starting from 0.

0

This is the evaluation:

middle = int(len(numbers)/2)
middle = int(5/2)
middle = int(2.5) # or int(2) depending on Python version
middle = 2

numbers[middle]
numbers[2]
6
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
0

The middle corresponds to the index at the middle of your numbers list. To find the median of the list, you can try to sort it first using numbers.sort(), like this:

def median(numbers):
    numbers.sort()
    middle = int(len(numbers)/2)
    return numbers[middle]

As an example, if numbers = [1,2,3,4,5,6], len(numbers) will evaluate to 6, which will be halved to 3 to define the middle index. Given that and knowing that a python list starting index is 0, the line return numbers[middle] will return the fourth element, which is 4.