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)
>>> 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
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.
+count() method returns the number of occurrences of a specific value in a list.
+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.
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.
-False, because 'c' is not a value in a_list.
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.
--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.
+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!
+