Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python | Custom Index Range Summation

  • Last Updated : 19 Feb, 2020

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 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]

 

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 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]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!