next up previous contents
Next: Functions and Methods for Up: List Operators Previous: Repetition   Contents

The in operator

The in operator provides a very convenient way to determine if a particular value is contained in a list. As its name implies, you provide a value on the left hand side of the operator, and a list on the right hand side; an expression so constructed will return 1 if the value is in the list and 0 otherwise, making it ideal for conditional statements (Section 6.4). The left hand side can be a literal value, or an expression; the value on the right hand side can be a list, or an expression that evaluates to a list.

Since python's lists are so flexible, you need to be careful about how you construct expressions involving the in operator; only matches of the same type and value will return a value of 1. Consider the list squarepairs, each of whose elements are a list consisting of a small integer and its square:

>>> squarepairs = [[0,0],[1,1],[2,4],[3,9]]
To see if a list containing the elements 2 and 4 is contained in the squarepairs list, we could use an expression like the following:
>>> [2,4] in squarepairs
1
Python responds with a 1, indicating that such a list is an element of squarepairs. But notice that neither element of the list alone would be found in squarepairs:
>>> 2 in squarepairs
0
>>> 4 in squarepairs
0
The in operator works just as well with expressions that evaluate to elements in a list:
>>> nums = [0,1,2,3,4,5]     
>>> [nums[2]] + [nums[4]] in squarepairs
1

The in operator is also used to iterate over the elements of a list in a for loop (Section 6.5).


next up previous contents
Next: Functions and Methods for Up: List Operators Previous: Repetition   Contents
Phil Spector 2003-11-12