Can we multiply 2 lists in Python?

4 Python ways to multiply the items in two lists

Python program to multiply the items in two lists:

In this post, we will learn how to create a new list by multiplying the items in two lists. This program will do index-wise multiplication i.e. the first item of the first list will be multiplied with the first item of the second list, the second item of the first list will be multiplied with the second item of the second list etc.

We can do this in different ways. Lets take a look at them one by one:

Method 1: By iterating the lists:

We can iterate one list and by using the iterating index, we can access the item at that index in the second list.

first_list = [1, 2, 3, 4, 5] second_list = [2, 3, 4, 5, 6] product_list = [] for i, v in enumerate[first_list]: product_list.append[first_list[i] * second_list[i]] print[f'First list: {first_list}'] print[f'Second list: {second_list}'] print[f'Product list: {product_list}']

Here,

  • first_list and second_list are given lists of numbers.
  • It iterates through the items of the first_list using a for loop and appends the product of first_list and second_list items to the product_list.
  • The last three lines are printing the content of the three lists created.

If you run this program, it will print the below output:

First list: [1, 2, 3, 4, 5] Second list: [2, 3, 4, 5, 6] Product list: [2, 6, 12, 20, 30]

Note that it will throw one error if the length of the second list is smaller than the first list. It will throw IndexError.

IndexError: list index out of range

To avoid that, you can wrap the code in a try-except block:

first_list = [1, 2, 3, 4, 5] second_list = [2, 3, 4, 5] product_list = [] for i, v in enumerate[first_list]: try: product_list.append[first_list[i] * second_list[i]] except IndexError: print['Error..Lengths are unequal !!'] print[f'First list: {first_list}'] print[f'Second list: {second_list}'] print[f'Product list: {product_list}']

It will print:

Error..Lengths are unequal !! First list: [1, 2, 3, 4, 5] Second list: [2, 3, 4, 5] Product list: [2, 6, 12, 20]

The length of the first list is 5 and the length of the second list is 4. The final list is created only for 4 items.

We can use list comprehension to do it quickly in just one line:

first_list = [1, 2, 3, 4, 5] second_list = [2, 3, 4, 5] product_list = [v * second_list[i] for i, v in enumerate[first_list] if i

Chủ Đề