VOOZH about

URL: https://www.geeksforgeeks.org/python/python-diagonal-element-addition-among-lists/

⇱ Python - Diagonal element addition among lists - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Diagonal element addition among lists

Last Updated : 12 Apr, 2023

Sometimes, while working with Python lists, we can have a problem in which we need to perform addition of lists in diagonal manner that i.e. adding ith element of 1 list to i + 1 element of other list. This kind of problem can have application in day-day programming. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using loop This is brute force way in which this task can be performed. In this, we iterate one list and test add the i + 1th element of other list and construct the resultant list. 

Output : 
The original list 1 is : [1, 6, 8, 5, 3]
The original list 2 is : [8, 10, 3, 4, 5]
List after diagonal addition : [11, 9, 12, 10]

Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using the loop which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list. 

  Method #2 : Using zip() + list comprehension This is yet another way in which this task can be performed. In this, we group ith with i+1th element of other list using zip(). The task of performing addition is done in list comprehension. 

Output : 
The original list 1 is : [1, 6, 8, 5, 3]
The original list 2 is : [8, 10, 3, 4, 5]
List after diagonal addition : [11, 9, 12, 10]

Time Complexity: O(n), where n is length of input list.
Auxiliary Space: O(n), where n is length of res list. 

Method #3 : Using Numpy
This method makes use of the functionality provided by numpy library in python. The library provides the numpy.add function which performs element wise addition of two arrays.

Output :
The original list 1 is : [1, 6, 8, 5, 3]
The original list 2 is : [8, 10, 3, 4, 5]
List after diagonal addition : [11, 9, 12, 10]

Time Complexity: O(n)
Auxiliary Space: O(n)

Explanation:
Here, the add function in numpy performs element wise addition of two arrays. The tlist function is used to convert the result array to a list. The time and space complexity is O(n) as we are iterating the two arrays and constructing a new resultant array.

Comment