diff --git a/native-datatypes.html b/native-datatypes.html index 932f461..502a16a 100644 --- a/native-datatypes.html +++ b/native-datatypes.html @@ -322,26 +322,30 @@ ZeroDivisionError: Fraction(0, 0)

Searching For Values In A List

 >>> a_list = ['a', 'b', 'new', 'mpilgrim', 'new']
->>> 'mpilgrim' in a_list      
-True
->>> a_list.index('mpilgrim')  
-3
->>> a_list.index('new')       
+>>> a_list.count('new')       
 2
->>> 'c' in a_list             
+>>> 'new' in a_list           
+True
+>>> 'c' in a_list
 False
->>> a_list.index('c')         
+>>> a_list.index('mpilgrim')  
+3
+>>> a_list.index('new')       
+2
+>>> a_list.index('c')         
 Traceback (innermost last):
   File "<interactive input>", line 1, in ?
 ValueError: list.index(x): x not in list
    -
  1. To test whether a value is in the list, use the in operator. It returns True if the value is in the list, or False if it is not. It will not tell you where in the list the value is. +
  2. As you might expect, the count() method returns the number of occurrences of a specific value in a list. +
  3. If all you want to know is whether a value is in the list or not, the in operator is slightly faster than using the count() method. The in operator always returns True or False; it will not tell you where in the list the value is.
  4. If you need to know exactly where in the list a value is, call the index() method. By default it will search the entire list, although you can specify a second argument of the (0-based) index to start from, and even a third argument of the (0-based) index to stop searching. -
  5. As you might expect, this will return False, because 'c' is not a value in a_list.
  6. The index() method finds the first occurrence of a value in the list. In this case, 'new' occurs twice in the list, in a_list[2] and a_list[4], but the index() method will return only the index of the first occurrence. -
  7. As you might not expect, if the value is not found in the list, Python raises an exception. This is notably different from most languages, which will return some invalid index (like -1). While this may seem annoying at first, I think you will come to appreciate it. It means your program will crash at the source of the problem instead of failing strangely and silently later. +
  8. As you might not expect, if the value is not found in the list, the index() method will raise an exception.
+

Wait, what? That’s right: the index() method raises an exception if it doesn’t find the value in the list. This is notably different from most languages, which will return some invalid index (like -1). While this may seem annoying at first, I think you will come to appreciate it. It means your program will crash at the source of the problem instead of failing strangely and silently later. Remember, -1 is a valid list index. If the index() method returned -1, that could lead to some not-so-fun debugging sessions! +

Removing Items From A List