How to Compute the Dot Product of Two Lists in Python
Compute the dot product of two equal-length numeric lists using a generator expression with zip and sum.
Python code
18 linesdef dot_product(list1, list2):
"""
Compute the dot product of two numeric lists.
The lists must have the same length.
"""
if len(list1) != len(list2):
raise ValueError("Lists must have the same length")
return sum(a * b for a, b in zip(list1, list2))
if __name__ == "__main__":
# Example usage
vector_a = [1, 2, 3]
vector_b = [4, 5, 6]
result = dot_product(vector_a, vector_b)
print(f"Dot product of {vector_a} and {vector_b} is {result}")
Output
Dot product of [1, 2, 3] and [4, 5, 6] is 32
How it works
The zip function pairs elements from both lists, creating tuples like (1, 4), (2, 5), and (3, 6). The generator expression a * b multiplies each pair, and sum adds all the products together. A ValueError is raised if the lists have different lengths, preventing silent incorrect results. This approach is concise and readable, leveraging Python's built-in functions.
Common mistakes
- Forgetting to check list lengths, leading to wrong results or errors
- Using `zip` without `sum`, so only the products are generated but not added
- Using `map` with a lambda instead of a generator expression, which is less readable
Variations
- Use `sum(map(lambda x, y: x * y, list1, list2))` for an alternative functional style
- Use `numpy.dot` if `numpy` is installed for larger arrays
- Use a manual `for` loop with an accumulator for clarity
Real-world use cases
- Computing the weighted sum of features in a machine learning model prediction.
- Calculating the inner product of two vectors in a physics or geometry application.
- Evaluating the sum of products in a financial portfolio allocation calculation.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.