Python Exercises: Sum of all list elements except current element
Python List: Exercise - 275 with Solution
Write a Python program to add all elements of a list of integers except the number at index. Return the updated string.
Example: ([1, 2, 3]) -> [1+2+3-1, 1+2+3-2, 1+2+3-3]
-> [5, 4, 3].
Sample Data:
([0, 9, 2, 4, 5, 6] -> [26, 17, 24, 22, 21, 20]
([-4, 0, 6, 1, 0, 2]) -> [9, 5, -1, 4, 5, 3]
([1, 2, 3]) -> [5, 4, 3]
([-4, 0, 5, 1, 0, 1]) -> [7, 3, -2, 2, 3, 2]
Sample Solution:
Python Code:
# Define a function named 'test' that takes a list 'nums' as input.
def test(nums):
# Use a list comprehension to calculate the sum of all elements in the 'nums' list,
# and then subtract each element 'x' from the total sum. This gives the sum of all elements except the current one.
return [sum(nums) - x for x in nums]
# Define the original list 'nums'.
nums = [0, 9, 2, 4, 5, 6]
print("Original list:")
print(nums)
# Call the 'test' function to calculate the sum of elements except the current element for each element in the list.
print("Sum of said list elements except the current element:\n", test(nums))
# Define another list 'nums'.
nums = [-4, 0, 6, 1, 0, 2]
print("\nOriginal list:")
print(nums)
# Call the 'test' function for the second list of numbers.
print("Sum of said list elements except the current element:\n", test(nums))
# Define another list 'nums'.
nums = [1, 2, 3]
print("\nOriginal list:")
print(nums)
# Call the 'test' function for the third list of numbers.
print("Sum of said list elements except the current element:\n", test(nums))
# Define another list 'nums'.
nums = [-4, 0, 5, 1, 0, 1]
print("\nOriginal list:")
print(nums)
# Call the 'test' function for the fourth list of numbers.
print("Sum of said list elements except the current element:\n", test(nums))
Sample Output:
Original list: [0, 9, 2, 4, 5, 6] Sum of said list elements except current element: [26, 17, 24, 22, 21, 20] Original list: [-4, 0, 6, 1, 0, 2] Sum of said list elements except current element: [9, 5, -1, 4, 5, 3] Original list: [1, 2, 3] Sum of said list elements except current element: [5, 4, 3] Original list: [-4, 0, 5, 1, 0, 1] Sum of said list elements except current element: [7, 3, -2, 2, 3, 2]
Flowchart:
Python Code Editor:
Previous Python Exercise: Count lowercase letters in a list of words.
Next Python Exercise: Find the largest odd number in a list of integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/list/python-data-type-list-exercise-275.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics