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.
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 list ini_list = [[3, 4, 7], [ 6, 7, 8], [ 10, 7, 5], [ 11, 12, 13]] # printing initial_list print ("initial_list ", ini_list) res = [] # Using Naive Method for sub_list in ini_list: sublistsum = 0 for i, value in enumerate(sub_list): sublistsum = sublistsum + i * value res.append(sublistsum) # printing result print ("result", res) |
chevron_right
filter_none
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 list ini_list = [[3, 4, 7], [ 6, 7, 8], [ 10, 7, 5], [ 11, 12, 13]] # printing initial_list print ("initial_list ", ini_list) # Using list comprehension res = [sum(i * j for i, j in enumerate(sublist)) for sublist in ini_list] # printing result print ("result", res) |
chevron_right
filter_none
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 list ini_list = [[3, 4, 7], [ 6, 7, 8], [ 10, 7, 5], [ 11, 12, 13]] # printing initial_list print ("initial_list ", ini_list) # Using numpy res = [np.arange(len(sublist)).dot(sublist) for sublist in ini_list] # printing result print ("result", res) |
chevron_right
filter_none
Output:
initial_list [[3, 4, 7], [6, 7, 8], [10, 7, 5], [11, 12, 13]] result [18, 23, 17, 38]
Recommended Posts:
- Python | Get last element of each sublist
- Python | Get first element of each sublist
- Python | Getting sublist element till N
- Python | Sort a list according to the second element in sublist
- Python | Get the Index of first element greater than K
- Python | Handling no element found in index()
- Python | Print list after removing element at given index
- Python | Indexing a sublist
- Python | Maximum Sum Sublist
- Python | Shift sublist in list
- Python | Split Sublist Strings
- Python | Replace sublist with other in list
- Python | Find maximum value in each sublist
- Python | Convert nested sublist into tuples
- Python | Remove sublists that are present in another sublist
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


