I'm currently doing a homework question:
Write and test a function
modify_listthat, given a list of floating point numbers as a parameter, computes the average of the values in the list and removes all values greater than the average from given list.
So far my code looks like this:
def modify_list(L):
    average = sum(L) / (len(L))
    j=0
    for J in L:
        if J>average:
            L.pop(J)
        else:
            j=j+1
L=[3,12,2,21,2,1,2]
modify_list(L)
print(L)
So far I have my list that is being passed to my function modify_list that then computes the average of my list. Then I have a for loop that takes each value in the list and compares it to the average. If the value within the list is greater than the average then it gets deleted through L.pop(J). The only problem is my error, which is:
Traceback (most recent call last):
  File "/Users/nathan/CP/test/src/test.py", line 22, in <module>
    modify_list(L)
  File "/Users/nathan/CP/test/src/test.py", line 17, in modify_list
    L.pop(J)
IndexError: pop index out of range
Should I maybe try a while loop instead of a for loop?
I created a while loop and it works perfectly... although L.remove(i) worked perfectly as well. I still don't understand why L.remove(i) is a bad idea. This is my new code:
1 def main(L):
2 average = sum(L) / (len(L))
3 i=0
4 while i
5 if L[i]>average:
6 L.pop(i)
7 else:
8 i=i+1
9
10 L=[3,12,2,21,2,1,2]
11 main(L)
12 print(L)
 
     
    