-2

I am trying to compare each element of the two equal length lists.

import numpy as np

def comp_one2one(list1, list2):
    tmp = []
    for i in range(len(list1)):
        if list2[i] > list1[i]:
            tmp.append(True)
        else: 
            tmp.append(False)
    return np.any(tmp)
list1 = [10, 15, 20]
list2 = [50, 10, 15] 
> print(comp_one2one(list1,list2))
True

I am wondering if there is a more efficient and more pythonic way of doing this operation?

Alex Man
  • 457
  • 4
  • 19

2 Answers2

1
def comp_one2one(list1, list2):    
    return all(np.array(list1)>np.array(list2))

edit: I missed the greater than, but you can change that to anything.

1

Lik Pranav mentioned, you can zip the two lists together

list1 = [10, 15, 20]
list2 = [50, 10, 15] 
tmp = []
for l1,l2 in zip(list1,list2):
    if l2 > l1:
        tmp.append(True)
    else: 
        tmp.append(False)
        
tmp
#[True, False, False]

Or you can try list comprehension

[l2>l1 for l1,l2 in zip(list1,list2)]

#[True, False, False]
willwrighteng
  • 1,411
  • 11
  • 25