 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Custom Multiplication in list of lists in Python
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
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
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]]
Advertisements
 