Search code examples
pythonpython-3.xmediannonetype

Why does using an index for a list return a "None Type not sub-scriptable error"?


I wrote a program that returns the median of a list of input. It takes in two inputs. First Input = number of elements Second input = elements

numElements = int(input())
elements = [int(num) for num in input().split(' ')]
elements = elements.sort()
if numElements % 2 == 0:
    medianOne = (numElements / 2) -1
    median = (elements[medianOne] + elements[medianOne + 1])/2
    print(median)
else:
    medianIndex = round(((float(numElements)/2)+0.2)) - 1
    median = elements[medianIndex]
    print(median)

When I supply an odd number of elements, I get a NoneType not subscriptable error. Why is this?


Solution

  • elements.sort() sorts the list in place. sorted(elements) returns a sorted array.

    That was the problem.