Python - when to use the in operator
Archive - Originally posted on "The Horse's Mouth" - 2006-08-16 07:39:35 - Graham EllisPython's in construct, when used with an if statement, lets you loop through all the members of a collection (such as a list or a tuple) and see if there's a member in the list that's equal to the pattern - thus
val = 17
if val in [1,4,5,7,12,14,17,20,34]: print "yes"
will print out "Yes". For looking for an element in a list, this is both quick coding and very efficient at run time, as the check is being done at a 'C level' - in other words, internally to Python without a constant series of reference back to the byte code. However - it IS still a loop.
Consider the following code which checks whether an integer entered by the user in between 0 and 30:
value = int(raw_input("Give me a number between 0 (inclusive) and 30 (exclusive): "))
if value in range(0,30): print "It is in range (1)"
if value < 30 and value >= 0: print "It is in range (2)"
if value in xrange(0,30): print "It is in range (3)"
All three work, and work well. BUT ... if the range we were checking was between 0 and 3 million, it would be a different story. The first test would create a list of 3 million integers internally and would then check our value against each of them - a real memory hog, and likely to break if the number was an order of magnitude higher that 3 million. The third test uses a generator function; not a memory hog, but never the less an internal loop looking at each number from 0 to 2,999,999 in turn and so really slow. The second test remains fast - just two checks to be made, no internal loop, no matter how high the top limit integer is!