[Tutor] misunderstanding "any"

Prasad, Ramit ramit.prasad at jpmorgan.com
Wed Mar 7 17:24:47 CET 2012


> >>> a = tuple(range(10))
> >>> b = tuple(reversed(a))
> 
> >>> any(a) in b
> True
> 
> >>> any(b) in a
> True
> 
> >>> any((a,b)) in (a,b)
> False  # I think I understand this now, but I must admit it looks
> confusing!



I just want to clarify some things. 'any(a) in b' evaluates any(a)
before it evaluates 'x in b'. So in essence 'any(a) in b' is 
equivalent to 'True in b'. 

The reason why you get True in the first two cases is because 
of Python's history where there were no bool types (I could be wrong 
on this). At the very least bool types inherit from integer in a 
common practice from older languages like C. Hopefully some of my 
samples will help explain my point.



>>> a = range(10)
>>> b = tuple( reversed( a ) )
>>> any(a) # Any non-zero value equates to true
True
>>> any(a) in b # True == 1
True
>>> True in b # True == 1
True
>>> any(b) # Any non-zero value equates to true
True
>>> True in a # True == 1
True
>>> True == 1 # Proof that True == 1
True
>>> False == 0 # Proof that False == 0
True
>>> any( (a,b) ) # many non-zero values
True
>>> a = range( 10,20 ) # create a list without 1
>>> b = tuple( reversed( a ) )
>>> any( a ) # still contains non-zero values
True
>>> any( a ) in b # b is missing the value 1 and therefore missing True
False
>>> any( b ) # still contains non-zero values
True
>>> any (b ) in a # a is missing the value 1 and therefore missing True
False
>>> any( (a,b) ) # still contains non-zero values
True
>>> any ( (a,b) ) in ( a,b ) # a and b is missing the value 1 
False
>>> any ( (a,b) ) in ( a,b, 1 ) # 1 == True
True


> Thinking that if  *any* of the tuples is in fruit_type(a list of
tuples), then it should return True.

What you want is not any, but probably filter or any + map.



>>> c = zip( a, b ) 
>>> c
[(10, 19), (11, 18), (12, 17), (13, 16), (14, 15), (15, 14), (16, 13), (17, 12), (18, 11), (19, 10)]
>>> d = ( 11, 18 )
>>> filter( lambda x: d == x, c )
[(11, 18)]
>>> 
>>> if filter( lambda x: d == x, c ):
...     print 'True'
...     
True
>>> map( lambda x: x==d, c )
[False, True, False, False, False, False, False, False, False, False]
>>> any( map( lambda x: x==d, c ) )
True


If you are comparing a list of tuples against a list of tuples merely change the above '==' to 'in' and d to be the second list of tuples and it should have similar results

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list