Python | Multiply each element in a sublist by its index
Given a list of lists, the task is to multiply each element in a sublist by its index and return a summed list.
Given below are a few methods to solve the problem.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Method #1: Using Naive Method
# Python3 code to demonstrate# to multiply numbers with position# and add them to return num import numpy as np # initialising listini_list = [[3, 4, 7], [ 6, 7, 8], [ 10, 7, 5], [ 11, 12, 13]] # printing initial_listprint ("initial_list ", ini_list) res = []# Using Naive Methodfor sub_list in ini_list: sublistsum = 0 for i, value in enumerate(sub_list): sublistsum = sublistsum + i * value res.append(sublistsum) # printing resultprint ("result", res) |
Output:
initial_list [[3, 4, 7], [6, 7, 8], [10, 7, 5], [11, 12, 13]] result [18, 23, 17, 38]
Method #2: Using List comprehension
# Python3 code to demonstrate# to multiply numbers with position# and add them to return num # initialising listini_list = [[3, 4, 7], [ 6, 7, 8], [ 10, 7, 5], [ 11, 12, 13]] # printing initial_listprint ("initial_list ", ini_list) # Using list comprehensionres = [sum(i * j for i, j in enumerate(sublist)) for sublist in ini_list] # printing resultprint ("result", res) |
Output:
initial_list [[3, 4, 7], [6, 7, 8], [10, 7, 5], [11, 12, 13]] result [18, 23, 17, 38]
Method #3: Using numpy
# Python3 code to demonstrate# to multiply numbers with position# and add them to return num import numpy as np # initialising listini_list = [[3, 4, 7], [ 6, 7, 8], [ 10, 7, 5], [ 11, 12, 13]] # printing initial_listprint ("initial_list ", ini_list) # Using numpyres = [np.arange(len(sublist)).dot(sublist) for sublist in ini_list] # printing resultprint ("result", res) |
Output:
initial_list [[3, 4, 7], [6, 7, 8], [10, 7, 5], [11, 12, 13]] result [18, 23, 17, 38]


