-1

I want to compare two lists. For example:

a = [8,9,9,11] 

b = [8,7,20,10]

if a >= b :

   print "true"

Why does this print "true"? I want to compare the values vertically like this:

8 >= 8 is true

9 >= 7 is true

9 >= 20 is false but the program return true

11 >= 10 is true
Ma0
  • 15,057
  • 4
  • 35
  • 65
NooK
  • 3
  • 2
  • You mean you want the result of the majority? – Bhushan Pant Nov 29 '17 at 08:26
  • 2
    Can you clarify what output you're looking for. Do you just want a result of `False`, or are you looking for a sequence, e.g., `(True, True, False, True)`? – Mark Dickinson Nov 29 '17 at 08:26
  • 1
    By default, tuples (or lists) are compared similar to how strings are compared: the comparison checks corresponding items until it finds a pair that aren't equal (or one collection runs out of items), and then the comparison stops. – PM 2Ring Nov 29 '17 at 08:31
  • @PM2Ring Then why is `True` returned? – Ma0 Nov 29 '17 at 08:33
  • 1
    @Ev.Kounis because first time two list element are not equal is `9` and `7` so it returns True and ignores other elements – ᴀʀᴍᴀɴ Nov 29 '17 at 08:35

2 Answers2

1

You can use list comprehension and all function as follows:

code:

a = 8,9,9,11 
b = 8,7,20,10
print all([(a > b) for a, b in zip(a,b)])

output:

False
Mahesh Karia
  • 2,045
  • 1
  • 12
  • 23
  • 2
    You should pass a generator expression to `all` or `any`, not a list comprehension. Both of those functions short-circuit, so they stop processing as soon as the result is clear. If you feed them a list comp the whole list has to be constructed before they start work, but if you feed them a gen exp then only as many items as are needed to determine the result will be generated. – PM 2Ring Nov 29 '17 at 08:35
0

You can use a list comprehension for comparing two lists element wise then use all function to check all of comparison are True:

a = [8,9,9,11]
b = [8,7,20,10]
all(a[i]>=b[i] for i in range(len(a))) # False
ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
  • 1
    Please see [my comment to Mahesh Karia](https://stackoverflow.com/questions/47548113/how-to-compare-8-9-9-11-vs-8-7-20-10#comment82053005_47548232) – PM 2Ring Nov 29 '17 at 08:36
  • 1
    Also, the OP (probably) doesn't want to compare every pair of elements, so that double for loop is incorrect. – PM 2Ring Nov 29 '17 at 08:38
  • @PM2Ring , Yeah I see your point , but since can not use `break` in list comprehension , how can I stop that when first `False` occurs (with list comprehension of course)? – ᴀʀᴍᴀɴ Nov 29 '17 at 08:40
  • 1
    You use a generator expression: `all(a[i]>=b[i] for i in range(len(a)))`. Even better, use direct iteration instead of indices: `all(a >= b for a, b in zip(a, b))`. And that will safely handle tuples that aren't the same length. – PM 2Ring Nov 29 '17 at 08:42