Python | Multiply each item in the sublist by its index

Here are some ways to solve the problem.

Method # 1: Using the naive method

# Python3 demo code
# multiply the numbers with position
# and add them to return num

 

import numpy as np

 
# initializing list

ini_list = [[ 3 , 4 , 7 ], [ 6 , 7 , 8 ], [ 10 , 7 , 5 ], [ 11 , 12 , 13 ]]

  
# print initial_list

print ( "initial_list" , ini_list)

  

res = []

# Using the naive method

for sub_list in ini_list:

sublistsum = 0

  

for i, value in enumerate (sub_list):

sublistsum = sublistsum + i * value

 

res.append (sublistsum)

  
# print result

print ( "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 the comprehension list

# Python3 demo code
# multiply the numbers with position
# and add them to return num

 

 
# initializing list

ini_list = [[ 3 , 4 < code class = "plain">, 7 ], [ 6 , 7 , 8 ], [ 10 , 7 , 5 ], [ 11 , 12 , 13 ]]

 
# print initial_list

print ( "initial_list" , ini_list)

  
# Using comprehension list

res = [ sum (i * j for i, j in enumerate (sublist)) 

  for sublist in ini_list]

 
# print result

print ( "result" , res)

  

Exit:

 initial_list [ [3, 4, 7], [6, 7, 8], [10, 7, 5], [11, 12, 13]] result [18, 23, 17, 38] 

Method # 3: Using NumPy

# Python3 demo code
# multiply the numbers with position
# and add them to return num

 

import numpy as np

 
# initializing list

ini_list = [[[ 3 , 4 , 7 ], [ 6 , 7 , 8 ], [ 10 , 7 , 5 ], [ 11 , 12 , 13 ]]

 
# print initial_list

print ( "initial_list" , ini_list)

 
# Using NumPy

res = [np.arange ( len (sublist)). dot (sublist) for sublist in ini_list]

  
# print result

print ( " result " , res)

  

  

Exit:

 initial_list [[3, 4, 7], [6, 7, 8], [10, 7, 5], [11, 12 , 13]] result [18, 23, 17, 38]