mirror of
https://github.com/kennethreitz/dive-into-python3.git
synced 2026-06-05 15:00:18 +00:00
clarify in vs. count vs. index
This commit is contained in:
@@ -337,8 +337,8 @@ ZeroDivisionError: Fraction(0, 0)</samp></pre>
|
||||
ValueError: list.index(x): x not in list</samp></pre>
|
||||
<ol>
|
||||
<li>As you might expect, the <code>count()</code> method returns the number of occurrences of a specific value in a list.
|
||||
<li>If all you want to know is whether a value is in the list or not, the <code>in</code> operator is slightly faster than using the <code>count()</code> method. The <code>in</code> operator always returns <code>True</code> or <code>False</code>; it will not tell you where in the list the value is.
|
||||
<li>If you need to know exactly where in the list a value is, call the <code>index()</code> 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.
|
||||
<li>If all you want to know is whether a value is in the list or not, the <code>in</code> operator is slightly faster than using the <code>count()</code> method. The <code>in</code> operator always returns <code>True</code> or <code>False</code>; it will not tell you how many times the value appears in the list.
|
||||
<li>Neither the <code>in</code> operator nor the <code>count()</code> method will tell you <em>where</em> in the list a value appears. If you need to know where in the list a value is, call the <code>index()</code> method. By default it will search the entire list, although you can specify an optional second argument of the (0-based) index to start from, and even an optional third argument of the (0-based) index to stop searching.
|
||||
<li>The <code>index()</code> method finds the <em>first</em> occurrence of a value in the list. In this case, <code>'new'</code> occurs twice in the list, in <code>a_list[2]</code> and <code>a_list[4]</code>, but the <code>index()</code> method will return only the index of the first occurrence.
|
||||
<li>As you might <em>not</em> expect, if the value is not found in the list, the <code>index()</code> method will raise an exception.
|
||||
</ol>
|
||||
|
||||
Reference in New Issue
Block a user