user9537546
user9537546

Reputation: 21

How to create a new list from values from a existing list

How do I create a new list with every score that is above the class average? extend doesn't work, but how do I add all the values that is above the average to the new list?

grades = [88, 95, 77, 75, 84, 65, 50, 100, 87, 84, 95, 96, 92, 81, 75]
sum1 = 0     
for x in grades: 
  sum1 += x  

numGrades = len(grades)

average = (sum1/numGrades)
print("The average for the class was: ",average)

aboveAve = []
num1 = 0
for x in grades: 
  if x >= average:
    aboveAve.extend(0)
print(aboveAve)

Upvotes: 0

Views: 59

Answers (3)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

You have to use

aboveAve.append(x)

instead of

aboveAve.extend(0)

For a shorter solution, you could use a list comprehension for this.

grades = [88, 95, 77, 75, 84, 65, 50, 100, 87, 84, 95, 96, 92, 81, 75]
average = sum(grades ) / len(grades)
aboveAve = [item for item in grades if item >= average]

Upvotes: 3

Timur
Timur

Reputation: 178

I think you need to replace aboveAve.extend(0) with aboveAve.extend([x])

Upvotes: 0

Data_Is_Everything
Data_Is_Everything

Reputation: 2016

You want to do this instead of extend:

 aboveAve.append(x) 

print(aboveAve) #in line with for loop

Upvotes: 0

Related Questions