Kentta
Kentta

Reputation: 45

Sorted list gone empty when statistics.median (Python) applied on it

I'm trying to use the Python statistics library but have trouble with median. As you can see below, the program return the mean, but the list somehow becomes empty for median and raises error. Please take a look, and thanks in advance!

import statistics

RawInput = input("Please enter a list separated by commas\n")
lst = RawInput.split(", ")
usable_lst = map(int, lst)


def mean():
    print("The mean is " + str(statistics.mean(usable_lst)))


def median():
    Sorted = sorted(usable_lst)
    print("The median is" + str(statistics.median(Sorted)))
    print("The median low is" + str(statistics.median_low(Sorted)))
    print("The median high is" + str(statistics.median_high(Sorted)))


def mode():
    print("The mode is" + str(statistics.mode(usable_lst)))


mean()
median()
mode()

Upvotes: 1

Views: 28

Answers (1)

David
David

Reputation: 8308

So the probelm is that usable_lst is a generator, and once you access it in the mean() function you empty it.

A fix can be to change usable_lst = map(int, lst) to usable_lst = list(map(int, last))

You can refer to the following links that might shed more light on the issue you are encountering:

Why can a python generator only be used once?

Resetting generator object in Python

How to make a repeating generator in Python

Upvotes: 1

Related Questions