Python | Custom Index Range Summation
Last Updated :
09 Apr, 2023
Development and sometimes machine learning applications require splitting lists into smaller list in a custom way, i.e on certain values on which split has to be performed and then summation. This is quite a useful utility to have knowledge about. Lets discuss certain ways in which this task can be performed.
Method #1: Using list comprehension + zip() + sum() By coupling the power of list comprehension and zip(), this task can be achieved. In this we zip beginning and end of list and then keep slicing the list as they arrive and cutting off new lists from them. The task of finding summation is performed using sum().
Python3
# Python3 code to demonstrate
# Custom Index Range Summation
# using list comprehension + zip() + sum()
# initializing string
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
# initializing split index list
split_list = [2, 5, 7]
# printing original list
print ("The original list is : " + str(test_list))
# printing original split index list
print ("The original split index list : " + str(split_list))
# using list comprehension + zip() + sum()
# Custom Index Range Summation
res = [sum(test_list[i : j]) for i, j in zip([0] +
split_list, split_list + [None])]
# printing result
print ("The splitted lists summation are : " + str(res))
Output : The original list is : [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
The original split index list : [2, 5, 7]
The splitted lists summation are : [5, 18, 8, 15]
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2: Using itertools.chain() + zip() + sum() The task performed by the list comprehension function of getting the split chunks can also be done using chain function. This is more useful when we wish to handle larger lists as this method is more efficient. The task of finding summation is performed using sum().
Python3
# Python3 code to demonstrate
# Custom Index Range Summation
# using itertools.chain() + zip()
from itertools import chain
# initializing string
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
# initializing split index list
split_list = [2, 5, 7]
# printing original list
print ("The original list is : " + str(test_list))
# printing original split index list
print ("The original split index list : " + str(split_list))
# using itertools.chain() + zip()
# Custom Index Range Summation
temp = zip(chain([0], split_list), chain(split_list, [None]))
res = list(sum(test_list[i : j]) for i, j in temp)
# printing result
print ("The splitted lists summations are : " + str(res))
Output : The original list is : [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
The original split index list : [2, 5, 7]
The splitted lists summation are : [5, 18, 8, 15]
Time Complexity: O(n*n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Method #3: Using numpy.split() + numpy.sum()
Note: Install numpy module using command "pip install numpy"
This method is using numpy library which makes the process of splitting and summation very simple and efficient.
Python3
import numpy as np
# initializing list
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
# initializing split index list
split_list = [2, 5, 7]
# printing original list
print ("The original list is : " + str(test_list))
# printing original split index list
print ("The original split index list : " + str(split_list))
# using numpy.split() + numpy.sum()
# Custom Index Range Summation
res = [np.sum(split) for split in np.split(test_list, split_list)]
# printing result
print ("The splitted lists summation are : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
Output:
The original list is : [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
The original split index list : [2, 5, 7]
The splitted lists summation are : [5, 18, 8, 15]
Time complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using a loop and slicing
This method uses a loop to iterate through the split index list and slice the original list based on the indices. The sum of each slice is then appended to the result list.
Python3
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
split_list = [2, 5, 7]
result = [] # initialize an empty list to store the results
start = 0 # initialize the starting index for slicing the original list
for end in split_list: # iterate through the split index list
# slice the original list from start to end, compute the sum, and append it to the result list
result.append(sum(test_list[start:end]))
start = end # update the starting index for the next slice
# slice the original list from the last split index to the end, compute the sum, and append it to the result list
result.append(sum(test_list[start:]))
print("The splitted lists summation are : " + str(result)) # print the result
OutputThe splitted lists summation are : [5, 18, 8, 15]
Time Complexity: O(n)
- The algorithm iterates through the split index list once, which takes O(k) time, where k is the length of the split index list.
- For each split index, the algorithm computes the sum of a slice of the original list, which takes O(n/k) time on average, where n is the length of the original list.
- Therefore, the overall time complexity of the algorithm is O(k * n/k) = O(n).
Auxiliary Space: O(k)
- The algorithm uses an additional list to store the results, which can have at most k elements, where k is the length of the split index list.
- Therefore, the overall space complexity of the algorithm is O(k).
Method #5: Using the reduce() function from functools module
The reduce() function can be used to apply a function to a sequence of values and return a single value. We can use it in combination with the split index list to compute the sum of each sublist. Here's an implementation using reduce():
Python3
from functools import reduce
# Initializing the input list
test_list = [1, 4, 5, 6, 7, 3, 5, 9, 2, 4]
# Initializing the split index list
split_list = [2, 5, 7]
# Initializing an empty list to store the sum of each sublist
result = []
# Initializing a variable to keep track of the starting index of each sublist
start = 0
# Looping through the split index list to compute the sum of each sublist
for end in split_list + [len(test_list)]:
# Using the reduce function to compute the sum of the current sublist
# The lambda function takes two arguments and returns their sum
# reduce() applies this function to each element of the sublist in a cumulative way
# and returns the final result
sublist_sum = reduce(lambda x, y: x + y, test_list[start:end])
# Appending the sum of the current sublist to the result list
result.append(sublist_sum)
# Updating the starting index of the next sublist
start = end
# Printing the result
print("The splitted lists summation are: " + str(result))
OutputThe splitted lists summation are: [5, 18, 8, 15]
Time complexity: O(n * m), where n is the length of the input list and m is the number of split indices. This is because we need to loop through the split index list and apply the reduce function to each sublist.
Auxiliary space: O(m), where m is the number of split indices.
Similar Reads
Python - Random Numbers Summation
We need to do summation of random numbers. For example, n = [random.randint(1, 10) for _ in range(5)] it will generate random numbers [4, 8, 9, 4, 6] between 1 to 10 so the resultant output should be 29.Using random.randint()random.randint(a, b) function generates a random integer between a and b (i
2 min read
Summation Matrix columns - Python
The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
2 min read
Element indices Summation - Python
Our task is to calculate the sum of elements at specific indices in a list. This means selecting elements at specific positions and computing their sum. Given a list and a set of indices, the goal is to compute the sum of elements present at those indices. For example, given the list [10, 20, 30, 40
3 min read
Python | Custom List slicing Sum
The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths and its summation according to the input given in other list. This problem has its potential application in web development. Letâs discuss certain ways in which this can be done. Me
7 min read
Python - Consecutive Row summation in Matrix
This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the sum between the like indices when compared with the next list. The sum between the like elements in that index is returned. Letâs discuss certain ways in which t
5 min read
Python | Selective indices Summation
Accessing an element from its index is easier task in python, just using the [] operator in a list does the trick. But in certain situations we are presented with tasks when we have more than once indices and we need to get all the elements corresponding to those indices and then perform the summati
6 min read
Python - Custom Tuple Key Summation in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform group summation of values, of certain key on particular index of tuple keys of dictionary. This problem is quite custom, but can have application in domains that revolves around data processing. Let'
7 min read
Python - Index Value Summation List
To access the elements of lists, there are various methods. But sometimes we may require to access the element along with the index on which it is found and compute its summation, and for that, we may need to employ different strategies. This article discusses some of those strategies. Method 1: Nai
4 min read
Python - Sort by range inclusion
Given a range, sort tuple Matrix by total range covered in a given range. [Considering tuples which completely lie within range]. Input : test_list = [[(1, 5), (6, 10), (10, 15)], [(3, 16)], [(2, 4), (6, 8), (9, 14)], [(1, 3), (9, 13)]], i, j = 2, 15 Output : [[(3, 16)], [(1, 5), (6, 10), (10, 15)],
4 min read
Python | Cumulative Columns summation of Records
Sometimes, while working with records, we can have a problem in which we need to sum all the columns of a container of lists which are tuples. This kind of application is common in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using sum() + list
7 min read