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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

18 lines
Python 3.9+
def 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

stdout
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

  1. Use `sum(map(lambda x, y: x * y, list1, list2))` for an alternative functional style
  2. Use `numpy.dot` if `numpy` is installed for larger arrays
  3. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.