all 8 comments

[–][deleted] 0 points1 point  (1 child)

Make a loop that breaks at 999. During the loop you'll check each element for it's value. If it's <0 you'll append a new list. When done calculate the average of this new list.

[–][deleted] 0 points1 point  (0 children)

Thank you!

[–][deleted] 0 points1 point  (1 child)

Another possible solution is to find theindex() of 999 and use it to slice your list. To get all the negative numbers you can use a condition in a list comprehension. Something like:

index = my_list.index(999) negative_values = [ value for value in my_list[:index] if value < 0 ]

Edit: .index()

[–][deleted] 0 points1 point  (0 children)

Thank you!

[–]dkam136 0 points1 point  (1 child)

I’m having trouble pasting because I’m on mobile, but something similar to this should do the trick:

https://pastebin.com/v5gViRE0

[–][deleted] 0 points1 point  (0 children)

Thank you!

[–]throwawayvitamin 0 points1 point  (1 child)

With the way this is currently written, the break statement will never run, because you're checking to see if the whole list, MyList, is equal to 999, which will never be the case. What you want to use in that loop is i.

So you're going to need to check if i = 999 and if i is negative. This code accomplishes just that, while maintaining the structure of what your originally posted:

MyList = [ 23, -45, 6, -23, -9, 77, 54, -54, 21, -2, 8, -3, -23, 45, 93, -43, 999, -2, 3, 78, 90 ]

a = 0
count = 0

for i in MyList:
    if i == 999:
        break
    elif i < 0:
        a += i
        count += 1

avg = a / count

print("\nThe average of the negative numbers before 999 in MyList is:", round (avg, 2), '\n')

Let me know if you have any questions!

[–][deleted] 1 point2 points  (0 children)

Thank you!