[Tutor] using in over several entities

Chris Calloway cbc at unc.edu
Fri Aug 24 20:47:56 CEST 2007


Alan Gauld wrote:
> "Chris Calloway" <cbc at unc.edu> wrote 
> 
>>>>> dbs = set(['oracle','mysql','postgres','infomix','access'])
>>>>> mine = set(['oracle','mysql','bdb'])
>>>>> dbs & mine
>> set(['oracle', 'mysql'])
>>>>> dbs - mine
>> set(['access', 'infomix', 'postgres'])
> 
> Interesting. I didn't know about the & and - set operations.
> Thanks for the pointer.

They just invoke special methods, of course:

s.issubset(t)                     s <= t   __le__
s.issuperset(t)                   s >= t   __ge__
s.union(t)                        s | t    __or__
s.intersection(t)                 s & t    __and__
s.difference(t)                   s - t    __sub__
s.symmetric_difference(t)         s ^ t    __xor__
s.update(t)                       s |= t   __ior__
s.intersection_update(t)          s &= t   __iand__
s.difference_update(t)            s -= t   __isub__
s.symmetric_difference_update(t)  s ^= t   __ixor__

Good times!

The advantage of the s.method(t) versions are, in Python 2.3.1 and
after, they will accept any, cough, iterable as argument t, whereas the
operator versions require set objects on both side of the operator:

 >>> set(xrange(10)).issubset(xrange(20))
True
 >>>

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599





More information about the Tutor mailing list