Multiply Consecutive elements in a list using Python


In the given problem statement we have to multiply the consecutive items in the given list with the help of Python programming language. So we will create the code using basic functionalities of Python.

Understanding the logic for the Problem

The problem at hand is to multiply each element with its adjacent element in the given list. So for multiplying the consecutive elements we will iterate over the list and multiply every element with the adjacent element. So basically we will start multiplying by the first item with the second item in the given list. And then the second item multiplied with the third item and so on. At the end the result will be a new list which will contain multiplied values. So let us see this process with an example below −

Algorithm

  • Step 1 − First we need to define the function to calculate the consecutive multiplication of the items in the given list. So let’s name the function as multiply_consecutives and pass an argument as the_list.

  • Step 2 − After creating the function we will define the empty list to store the multiplied values and give it a name as multiplied_result.

  • Step 3 − Next we will iterate over each item of the_list from 0th index to the (n-2)th index, here n is the size of the given input list.

  • Step 4 − Inside the loop we will multiply the current item with the next item and append the result in the new list we have created above multiplied_result.

  • Step 5 − And when the loop will be ended then we will return the new list multiplied_result which contains the multiplied values of the elements of the list.

Example

# define the function to calculate the multiplication of consecutives
def multiply_consecutives(the_list):

   # initialize the result of multiplied elements
   multiplied_result = []

   # iterated the list items
   for i in range(len(the_list) - 1):
      multiplied_value = the_list[i] * the_list[i + 1]
      multiplied_result.append(multiplied_value)
      return multiplied_result

# Example usage
the_list = [3, 6, 9, 12, 15]
multiply_Output = multiply_consecutives(the_list)
print(multiply_Output)

Output

[18]

Complexity

The time complexity for multiplying consecutive items in a list with Python is O(n), here n is the size of the given input list. As we have used the loop to iterate through the items of the list and performed a constant time operation so the complexity is linear.

Conclusion

So we have learned how to multiply consecutive elements in the given list using Python. As we have followed a simple and efficient way to get the desired result with the linear time complexity.

Updated on: 16-Oct-2023

47 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements