0

I am trying to work out the average sum of a list without index 0, is this possible in python? as you can see below, my list includes 1 name and 4 numbers. can I work out the average of the 4 numbers without including the name?

student = [Dan, 60, 70, 80, 90]

I have tried to achieve this in a number of different ways such as copying the list and removing index 0 however, this wasn't sufficient as I need this function to be looped a number of times inputted by the user previously.

I also tried to use the sum(student)/len(student) but that also gave an error as the list is a mix of int and str

  • 2
    get `student[1:]` – furas Feb 12 '21 at 18:52
  • 3
    `sum(student[1:])/(len(student)-1)`. That said - maybe you need to reconsider the data structure you use? – buran Feb 12 '21 at 18:53
  • 1
    Have you tried *anything at all*? – juanpa.arrivillaga Feb 12 '21 at 18:54
  • 1
    Welcome to stack overflow. Unfortunately this is not a code writing or tutorial service, and we ask that you include in your question _code_ for what you've tried based on your own research, and what went wrong with your attempts. See [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – G. Anderson Feb 12 '21 at 18:54
  • 1
    Thumbs up to @furas's comment above. The key take away here is that you can create a new list that excludes the first element with the slice operation `student[1:]`. Beyond that, the details of what you want to do with that new list is another question. – CryptoFool Feb 12 '21 at 19:01

2 Answers2

2

Try excluding the first element, you can achive that with:

studentWithoutFirstElement = student[1:]

Then you can calculate the mean doing the following:

sum(studentWithoutFirstRow)/len(studentWithoutFirstRow)

You can also use the function provided by the numpy library by typing:

import numpy as np
np.mean(studentWithoutFirstRow)
0

You can use this code for general case not only for your case.

sum_ = 0
count = 0
for i in student:
    if type(i) == int or type(i) == float:
        sum_ += i
        count += 1

avg = sum_/count

This code loop though list and check whether the type of element is int/float or not, if so adds it to sum and increase count by one. Finally you just divide sum to count.

Rustam Garayev
  • 2,632
  • 1
  • 9
  • 13