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

Viewed 56
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.

5 Answers

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)))

Can be done very simply with numpy if you wish:

np.min((a1, a2), axis=0)

Where a1 and a2 are numpy arrays, and a third (min) array is returned.

You can just use the iteration variables num1 and num2.

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

arr_1=[5, 9, 3]  
arr_2=[2, 16, 4] 

arr_3 = func_0(arr_1, arr_2)

print(arr_3)

[2, 9, 3]

num1 and num2 contains element from list so no need to write as arr_1[num1] and arr_2[num2])

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

Though you can use min() function to get minimum value between two.

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

I'd just use a basic list-comprehension:

def func_1(a1, a2):
    return [min(x, y) for (x, y) in zip(a1, a2)]

First list comprehensions make code easier to read, second it's often faster than other builtins.

Related