Compare items at the same index between 2 lists and append the min value to a 3rd list?

def func_0(arr_1, arr_2):
    arr_3 = list()
    for num1, num2 in zip(arr_1, arr_2):
        if(arr_1[num1]<=arr_2[num2]):
            arr_3.append(arr_1[num1])
        else:
            arr_3.append(arr_2[num2])
    return arr_3

Let’s say the first list arr_1=[5,9,3] and the second one arr_2=[2,16,4]. The output should be arr_3=[2,9,3] and I’ve been trying to use a for loop to compare the 2 values on the same index from 2 different lists and append the lesser value to a 3rd list but I can’t get the hang of it.

Answer

You made it too complicated, just append the min of each pair of numbers that the zip function produces.

def func_0(arr_1, arr_2):
    arr_3 = list()
    for pair in zip(arr_1, arr_2):
        arr_3.append(min(pair))
    return arr_3

If you want to make it really short, you can use:

def func_1(a1, a2):
    return list(map(min, zip(a1, a2)))

Leave a Reply

Your email address will not be published. Required fields are marked *