When it is required to redistribute the trimmed values, a list comprehension and the ‘/’ operator are used.
Example
Below is a demonstration of the same
my_list = [11, 26, 24, 75, 96, 37, 48, 29, 93] print("The list is :") print(my_list) key = 2 print("The value of key is") print(key) full_sum = sum(my_list) trimmed_list = my_list[key:len(my_list) - key] trim_sum = sum(trimmed_list) add_value = (full_sum - trim_sum) / len(trimmed_list) result = [ele + add_value for ele in trimmed_list] print("The resultant list is:") print(result)
Output
The list is : [11, 26, 24, 75, 96, 37, 48, 29, 93] The value of key is 2 The resultant list is: [55.8, 106.8, 127.8, 68.8, 79.8]
Explanation
A list is defined and is displayed on the console.
The value for key is defined and is displayed on the console.
The elements of the list are summed using the ‘sum’ method.
This result is assigned to a variable.
List comprehension is used to iterate over the length within a specific range.
This is also summed and assigned to a varibale.
The ‘/’ operator is used to get the value that needs to be added.
This is the difference between sum of list and sum of list in a specific range, and dividing this by the length of the list which has sum within a specific range.
A list comprehension is used to add the element of the list in a specific range to the value that needs to be added.
This is assigned to a variable.
This is displayed as the output on the console.