Custom Multiplication in list of lists in Python

Multiplying elements in a list of lists (nested list) with corresponding elements from another list is a common operation in data analysis. Python provides several approaches to perform this custom multiplication efficiently.

Using Nested Loops

In this approach, we use two nested for loops. The outer loop iterates through each sublist, while the inner loop multiplies each element in the sublist with the corresponding multiplier ?

nested_list = [[2, 11, 5], [3, 2, 8], [11, 9, 8]]
multipliers = [5, 11, 0]

# Original list
print("The given list:", nested_list)
print("Multiplier list:", multipliers)

# Using nested loops
result = [[] for idx in range(len(nested_list))]
for i in range(len(nested_list)):
    for j in range(len(nested_list[i])):
        result[i].append(multipliers[i] * nested_list[i][j])

print("Result of multiplication:", 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]]

Using enumerate() with List Comprehension

The enumerate() function provides both the index and value of each sublist, making the code more concise and readable ?

nested_list = [[2, 11, 5], [3, 2, 8], [11, 9, 8]]
multipliers = [5, 11, 0]

print("The given list:", nested_list)
print("Multiplier list:", multipliers)

# Using enumerate with list comprehension
result = [[multipliers[i] * element for element in sublist]
          for i, sublist in enumerate(nested_list)]

print("Result of multiplication:", 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]]

Using zip() Function

The zip() function pairs each sublist with its corresponding multiplier, creating cleaner code ?

nested_list = [[2, 11, 5], [3, 2, 8], [11, 9, 8]]
multipliers = [5, 11, 0]

print("The given list:", nested_list)
print("Multiplier list:", multipliers)

# Using zip with list comprehension
result = [[multiplier * element for element in sublist]
          for sublist, multiplier in zip(nested_list, multipliers)]

print("Result of multiplication:", 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]]

Comparison

Method Readability Performance Best For
Nested Loops Good Slower Beginners, complex logic
enumerate() Better Faster When you need indices
zip() Best Fastest Clean, Pythonic code

Conclusion

For custom multiplication in nested lists, zip() with list comprehension offers the most readable and efficient solution. Use nested loops for complex operations and enumerate() when you need both index and value access.

Updated on: 2026-03-15T18:22:48+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements