Python program to find the sum of a Sublist
Last Updated :
27 Jul, 2023
Given a list of numbers, write a Python program to find the sum of all the elements in the list.
Examples:
Input: arr = [2,4,5,10], i = 1, j = 3
Output: 19
Input: arr = [4,10,5,3,3], i = 3, j = 3
Output: 3
Find the sum of a Sublist Applying Brute Force
In this method, we will be initializing an output variable, say ans=0. Then initialize a loop from index i to j and add the list element to the output.
Python3
l = [ 4 , 10 , 5 , 3 , 3 ]
i = 3
j = 3
ans = 0
for i in range (i, j + 1 ):
ans + = l[i]
print (ans)
|
Output:
3
Time Complexity: O(n)
Auxiliary Space: O(1)
Find the sum of a Sublist By using the Cumulative Technique
The cumulative sum technique is used to add all the previous element values to the current index value.
Python3
l = [ 2 , 4 , 5 , 10 ]
i = 1
j = 3
for x in range ( len (l)):
if (x = = 0 ):
continue
else :
l[x] = l[x] + l[x - 1 ]
if (i = = 0 ):
print (l[j])
else :
print (l[j] - l[i - 1 ])
|
Output :
19
Find the sum of a Sublist By using sum() function
sum() function is used to calculate the sum of the list. It takes input as the sub-list.
Python3
l = [ 2 , 4 , 5 , 10 ]
i = 1
j = 3
print ( sum (l[i:j + 1 ]))
|
Output :
19
Time Complexity: O(n)
Auxiliary Space: O(n), where n is number of elements in list.
Find the sum of a Sublist By using Math Module
Math module has a special function name fsum(). It also takes the input as the sublist. Then we can use fsum() function, to calculate the sum of the sub-list.
Python3
l = [ 4 , 10 , 5 , 3 , 3 ]
i = 3
j = 3
sum = math.fsum(l[i:j + 1 ])
print ( sum )
|
Output :
3
Find the sum of a Sublist using Recursion
A new approach to finding the sum of a sublist would be to use recursive programming, where a recursive function is called on itself to continually add the current element of the sublist to a running total until the end of the sublist is reached.
Python3
def sublist_sum(l, i, j):
if (i = = j):
return l[i]
return l[i] + sublist_sum(l, i + 1 , j)
l = [ 2 , 4 , 5 , 10 ]
i = 1
j = 3
print (sublist_sum(l, i, j))
|
Time complexity of the sublist_sum() function is O(n), where n is the length of the input list,
Auxiliary Space: O(n).
Find the sum of a Sublist using Slice notation
This problem can be solved using Python’s slice notation. This method allows you to extract a portion of the list between the start and end indices, and then use the built-in sum() function to calculate the sum of the sublist.
Python3
l = [ 4 , 10 , 5 , 3 , 3 ]
i = 3
j = 3
sublist = l[i:j + 1 ]
ans = sum (sublist)
print (ans)
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...