On 26/07/13 09:50, Albert-Jan Roskam wrote:
if I have d = {1: 2}, I can do membership testing in the following
> two ways --but which one is the preferred way?:
if 1 in d: pass if d.has_key(1): pass
In addition to being more readable (and the fact it's the only way in v3) 'in' has another big advantage - it's polymorphic:
holds_1 = [] bigBox = [ {1:2,3:4}, ['a',2,;freddy',True], (1,2,3) ] for collection in bigBox: if 1 in collection: holds_1.append(collection) You can't do that using has_key(), the code has to test for dict type etc. So all in all 'in' is the way to go. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor