Search code examples
pythonadditionelementwise-operations

I basically want to do an element-wise addition but using only for loops, so no numpy or map


Here's what I want the layout to look. I want it to be a function so I can use it in the cmd prompt. The lengths of each list have to be the same, if not it should return none

def add_elements(list1, list2):
     if len(list1)==len(list2):
          for i in list1:
     else:
          None

I dont know if the "for i in list1:" is what I should use, if so what comes after?


Solution

  • If I understand you correctly I think this is what your looking for:

    def add_elements(list1, list2):
        if len(list1) == len(list2):
    
            results = []
            for i in range (len(list1)):
                results.append(list1[i] + list2[i])
    
            return results
    
        else:
            return None
    
    
    l1 = [1,2,3,4]
    l2 = [5,6,7,8]
    l3 = [1,2,3,4,5,6]
    
    print(add_elements(l1, l2))
    print(add_elements(l1, l3)
    

    If the lists are the same length, the for loop will iterate over the length of the lists adding the elements. The last few lines (outside the function definition) will prove that the function works. The first print statement will give you the resulting list. The second print statement will show 'None' because l1 and l3 are different lengths.

    I hope this is helpful.