AppDividend
Latest Code Tutorials

Python List Multiply: How to Multiply Lists in Python

0

If you were working in Python, then there are lots of scenarios where one requires to find index-wise products of two different lists. Let’s see how to multiply lists in Python step by step using different approaches.

Python List Multiply

To multiply lists in Python, use the zip() function. You need to pass the lists into the zip(*iterables) function to get a list of tuples that pair elements with the same position from both lists.

The zip() is a built-in Python function that creates an iterator that will aggregate elements from two or more iterables.

listA = [1, 2, 3]
listB = [4, 5, 6]
products = []


for dt1, dt2 in zip(listA, listB):
    products.append(dt1 * dt2)

print(products)

Output

[4, 10, 18]

In this example, first, we defined two lists. Then passed both lists into the zip() method to get a list of tuples that pair elements with the same position from both lists. Use a for loop to multiply these elements together and append them to a new list.

Using list comprehension to multiply the list

List comprehension allows a shorter syntax when you want to create a new list based on the values of an existing list. Without list comprehension, you will have to write a for loop with a conditional test inside, as we saw in the above section’s example.

You can use list comprehension to multiply lists in Python. Initialize the product’s value to 1(not 0 as 0 multiplied with anything that returns zero). Traverse till the end of the list, multiply every number with the product.

Syntax of List Comprehension

[expression for item in list]

Example of list multiply

listA = [1, 2, 3]
listB = [4, 5, 6]

products = [x * y for x, y in zip(listA, listB)]
print(products)

Output

[4, 10, 18]

And we get the new multiplied list from the two lists in the output.

That is it for this tutorial.

See also

Python list count()

Python list contains

Python list reverse

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.