python - A function that recieves three numbers and a list, gets an average of those three numbers and subtracts the average from each number on the list -


i've got question regarding how improve small wrote. i'm new python , tried make loop failed, wondering if there more efficient way write function(i wanted loop if u guys have better idea i'd appreciate if posted it). thanks! btw, list recieved numbers, there aren't strings, chars, etc.

def newlist(n1,n2,n3,list):     avg = (n1+n2+n3)/3     i=0     while i<len(list):         list[i] -= avg         += 1     print d 

python’s list comprehensions useful when want perform same operation on every item in list. example, suppose had list of numbers defined follows:

list_of_numbers = [1, 2, 3, 4, 5] 

to add 5 every number in list , put variable called new_list, you’d use list comprehension:

new_list = [number + 5 number in list_of_numbers] 

if check value of new_list, you’ll see is:

[6, 7, 8, 9, 10] 

you can use list comprehension in newlist() method:

def newlist(n1, n2, n3, list):   average = (n1 + n2 + n3) / 3   result_list = [item - average item in list]   return result_list 

when call so:

newlist(1, 2, 3, [4, 5, 6]) 

you’ll result:

[2, 3, 4] 

Comments