Custom Multiplication in list of lists in Python

PythonServer Side ProgrammingProgramming

Multiplying two lists in python can be a necessity in many data analysis calculations. In this article we will see how to multiply the elements of a list of lists also called a nested list with another list.

Using Loops

In this approach we design tow for loops, one inside another. The outer loop keeps track of number of elements in the list and the inner loop keeps track of each element inside the nested list. We use the * operator to multiply the elements of the second list with respective elements of the nested list.

Example

 Live Demo

listA = [[2, 11, 5], [3, 2, 8], [11, 9, 8]]

multipliers = [5, 11, 0]

# Original list
print("The given list: " ,listA)

# Multiplier list
print(" Multiplier list : " ,multipliers )

# using loops
res = [[] for idx in range(len(listA))]
   for i in range(len(listA)):
      for j in range(len(multipliers)):
         res[i] += [multipliers[i] * listA[i][j]]

#Result
print("Result of multiplication : ",res)

Output

Running the above code gives us the following result −

The given list: [[2, 11, 5], [3, 2, 8], [11, 9, 8]]
Multiplier list : [5, 11, 0]
Result of multiplication : [[10, 55, 25], [33, 22, 88], [0, 0, 0]]

With enumerate

The enumerate method can be used to fetch each element of the nested list and then for loops can be used to do the multiplication.

Example

 Live Demo

listA = [[2, 11, 5], [3, 2, 8], [11, 9, 8]]

multipliers = [5, 11, 0]

# Original list
print("The given list: " + str(listA))

# Multiplier list
print(" Multiplier list : " ,multipliers )

# Using enumerate
res = [[multipliers[i] * j for j in x]
      for i, x in enumerate(listA)]

   #Result
print("Result of multiplication : ",res)

Output

Running the above code gives us the following result −

The given list: [[2, 11, 5], [3, 2, 8], [11, 9, 8]]
Multiplier list : [5, 11, 0]
Result of multiplication : [[10, 55, 25], [33, 22, 88], [0, 0, 0]]
raja
Published on 26-Aug-2020 10:28:28
Advertisements