0

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?

2 Answers2

2

Use the list index in your for loop

list1 = [1,2,3,4,5]
list2 = [5,4,3,2,1]

def add_elements(list1, list2):
     if len(list1) != len(list2): return None
     lst = []
     if len(list1)==len(list2):
          for i in range(len(list1)):
             lst.append(list1[i] + list2[i])
     return lst
          
print(add_elements(list1, list2))

Output

[6, 6, 6, 6, 6]

If the zip function is permitted, this is faster:

list1 = [1,2,3,4,5]
list2 = [5,4,3,2,1]

lst = [a+b for a,b in zip(list1, list2)]
print(lst)

Output

[6, 6, 6, 6, 6]
Mike67
  • 11,175
  • 2
  • 7
  • 15
0

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.

Eric Feight
  • 116
  • 6