Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python List index()

#1
Python List index()

<div><p>This tutorial shows you everything you need to know to help you master the essential <code>index()</code> method of the most fundamental container data type in the Python programming language.</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="python list count" width="1400" height="788" src="https://www.youtube.com/embed/6OAQ6eJWbVE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>Definition and Usage: The <code>list.index(value)</code> method returns the index of the <code>value</code> argument in the <code>list</code>. You can use optional <code>start</code> and <code>stop</code> arguments to limit the index range where to search for the value in the list. If the value is not in the list, the method throws a <code>ValueError</code>. </strong></p>
<p>Here’s a short example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst = ["Alice", 42, "Bob", 99]
>>> lst.index("Alice")
0
>>> lst.index(99)
3
>>> lst.index(99, 1, 3) Traceback (most recent call last): File "&lt;pyshell#9>", line 1, in &lt;module> lst.index(99, 1, 3)
ValueError: 99 is not in list</pre>
<p>In the first line of the example, you create the list <code>lst</code>. You then look up the index of the elements <code>"Alice"</code> and <code>99</code>. If you use <code>start=1</code> and <code>stop=3</code>, the value <code>99</code> is not found anymore and Python throws a <code>ValueError</code>.</p>
<p><strong>Code Puzzle — Try It Yourself:</strong></p>
<p>Now you know the basics. Let’s deepen your understanding with a short code puzzle—can you solve it?</p>
<p> <iframe height="600px" width="100%" src="https://repl.it/@finxter/PythonListIndex?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p>
<p><a href="https://app.finxter.com/learn/computer/science/576" target="_blank" rel="noreferrer noopener">You can also solve this puzzle and track your Python skills on our interactive Finxter app.</a></p>
<p><strong>Syntax</strong>: You can call this method on each list object in Python (<a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-check-your-python-version/" target="_blank">Python versions 2.x and 3.x</a>). Here’s the syntax:</p>
<p><code>list.index(value, start=0, stop=9223372036854775807)</code></p>
<p><strong>Arguments:</strong></p>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Argument</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>value</code></td>
<td>Returns the index of <code>value</code> in the <code>list</code>. A value appears in the list if the <code>==</code> operator returns <code>True</code>. If the value doesn’t exist in the list, the return value is <code>-1</code>. </td>
</tr>
<tr>
<td><code>start</code></td>
<td>(Optional.) The index of where you want to start searching in the list. All list elements in front of this position are ignored. This is a positional argument, not a keyword argument.</td>
</tr>
<tr>
<td><code>stop</code></td>
<td>(Optional.) The index of where you want to stop searching in the list. All list elements after this position are ignored. This is a positional argument, not a keyword argument.</td>
</tr>
</tbody>
</table>
</figure>
<p><strong>Return value:</strong> The method <code>list.index(value)</code> returns an integer value representing the index where the argument <code>value</code> appears in the list. If the value does not appear in the list, the method throws a <code>ValueError</code>. </p>
<p><strong>Related article:</strong> <a rel="noreferrer noopener" href="https://blog.finxter.com/python-regex/" target="_blank">Python Regex Superpower – The Ultimate Guide</a></p>
<h2>Python List Index Implementation</h2>
<h2>Python List Index Time Complexity</h2>
<h2>Python List Index Out of Range</h2>
<h2>Python List Index Without Exception</h2>
<h2>Python List Index Try Catch</h2>
<h2>Python List Index Multiple</h2>
<h2>Python List Index Range</h2>
<h2>Python List Index of Max / Min</h2>
<h2>Python List Index From End (Reverse)</h2>
<h2>Python List Index Regex</h2>
<h2>Python List Index Wildcard</h2>
<h2>Python List Index Enumerate</h2>
<h2>Python List Index Exclude</h2>
<h2>Python List Index Tuple</h2>
<h2>Python List Index True False</h2>
<h2>Python List Index Zero / Non-Zero</h2>
<h2>Python List Index Pop</h2>
<h2>Python List Index Delete</h2>
<h2>Python List Index Slice / Substring</h2>
<h2>Python List Index By Value / Key / Array / Tuple</h2>
<h2>Python List Index Multidimensional</h2>
</p>
<p><strong>Related articles:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/python-list-methods/">Python List Methods – A Simple Overview</a></li>
<li><a href="https://blog.finxter.com/how-to-start-learning-python-no-bs-guide/" target="_blank" rel="noreferrer noopener">How to Start Learning Python?</a></li>
</ul>
<h2>Python List Count Runtime Complexity</h2>
<p>The <a rel="noreferrer noopener" href="https://wiki.python.org/moin/TimeComplexity" target="_blank">time complexity</a> of the <code>count(value)</code> method is O(n) for a list with n elements. The standard Python implementation <a rel="noreferrer noopener" href="https://github.com/python/cpython" target="_blank">cPython </a>“touches” all elements in the original list to check if they are equal to the value. </p>
<p>Again, have a look at the reference implementation where you can see these comparison operations <code>element == value</code> in the code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def count(lst, value): count = 0 for element in lst: count += element == value return count</pre>
<p>Thus, the time complexity is linear in the number of list elements. </p>
<p>You can see a plot of the time complexity of the <code>count()</code> method for growing list size here:</p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/03/image-26.png" alt="" class="wp-image-7029" srcset="https://blog.finxter.com/wp-content/uploads/2020/03/image-26.png 725w, https://blog.finxter.com/wp-content/uplo...00x224.png 300w" sizes="(max-width: 725px) 100vw, 725px" /></figure>
<p><em>The figure shows how the elapsed time of counting a dummy element -99 in lists with growing number of elements grows linear to the number of elements.</em></p>
<p>If you’re interested in the code I used to generate this plot with <a href="https://blog.finxter.com/matplotlib-line-plot/" target="_blank" rel="noreferrer noopener">Matplotlib</a>, this is it:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import matplotlib.pyplot as plt
import time y = []
for i in [100000 * j for j in range(10,100)]: lst = list(range(i)) t0 = time.time() x = lst.count(-99) t1 = time.time() y.append(t1-t0) plt.plot(y)
plt.xlabel("List elements (10**5)")
plt.ylabel("Time (sec)")
plt.show()
</pre>
<h2>Python List Count Duplicates</h2>
<p>How can you count the number of duplicates in a given list? </p>
<p><strong>Problem</strong>: Let’s consider an element a duplicate if it appears at least two times in the list. For example, the list <code>[1, 1, 1, 2, 2, 3]</code> has two duplicates <code>1</code> and <code>2</code>. </p>
<p><strong>Solution</strong>: You create an <a href="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener">empty set</a> duplicates. Then you iterate over the original list and add each element to the set that has a count value of at least 2. </p>
<p>Here’s the code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def find_dups(lst): dups = set() for el in lst: if lst.count(el)>1: dups.add(el) return dups print(find_dups([1, 1, 1, 2, 2, 3]))
# {1, 2} print(find_dups(["Alice", "Bob", "Alice"]))
# {'Alice'} print(find_dups([1, 2, 3]))
# set()</pre>
<p>Note that this algorithm has quadratic time complexity because for each element in the list, you need to count the number of times it appears in the list—each of those count operations has linear time complexity.</p>
<p><strong>Related article:</strong></p>
<ul>
<li><a href="https://blog.finxter.com/sets-in-python/" target="_blank" rel="noreferrer noopener">An Introduction to Sets in Python (Harry Potter Examples) <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f609.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></a></li>
</ul>
<h2>Python List Count Unique Values and Strings</h2>
<p>How can you count the <em>number of unique values</em> (or strings) in a given list?</p>
<p><strong>Problem</strong>: A value is considered unique if it appears only once in the list.</p>
<p><strong>Solution</strong>: You count each <code>element</code> in the list and take only those with <code>list.count(element) == 1</code>. </p>
<p>Here’s the code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def find_uniques(lst): uniques = set() for el in lst: if lst.count(el) == 1: uniques.add(el) return uniques print(find_uniques([1, 1, 2, 3, 3]))
# {2} print(find_uniques(["Alice", "Bob", "Alice"]))
# {'Bob'}</pre>
<p>This algorithm has quadratic time complexity because for each element in the list, you need to count the number of times it appears in the list—each of those count operations has linear time complexity.</p>
<h2>Python List Count All Elements (Count to Dict)</h2>
<p>How can you count all elements in a list and store the result in a dictionary?</p>
<p><strong>Problem</strong>: Given is a list. You want to count each element in the list. Then, you want to store the result in a dictionary mapping the elements to their frequencies of appearance (counts). For example, the list <code>[1, 1, 2, 2, 3]</code> should lead to the dictionary <code>{1:2, 2:2, 3:1}</code>. </p>
<p><strong>Solution</strong>: You solve this problem using <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" target="_blank">dictionary comprehension</a>. The key is the list element and the value is the frequency of this element in the list. You use the <code>count()</code> method to do this.</p>
<p>Here’s the code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def count_to_dict(lst): return {k:lst.count(k) for k in lst} print(count_to_dict(["Alice", "Bob", "Ann", "Alice", "Charles"]))
# {'Alice': 2, 'Bob': 1, 'Ann': 1, 'Charles': 1} print(count_to_dict([1, 1, 1, 2, 2, 3]))
# {1: 3, 2: 2, 3: 1}</pre>
<p>This algorithm has quadratic time complexity because for each element in the list, you need to count the number of times it appears in the list—each of those count operations has linear time complexity.</p>
<p><strong>Related article:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" target="_blank">Ultimate Guide to Dictionaries in Python</a></li>
</ul>
<h2>Python List Count With Condition</h2>
<p>How can you count elements under a certain condition in <a href="https://blog.finxter.com/python-crash-course/" target="_blank" rel="noreferrer noopener">Python</a>? For example, what if you want to count all even values in a list? Or all prime numbers? Or all strings that start with a certain character? There are multiple ways to accomplish this, let’s discuss them one by one.</p>
<p>Say, you have a condition for each element <code>x</code>. Let’s make it a function with the name <code>condition(x)</code>. You can define any condition you want—just put it in your function. For example this condition returns True for all elements that are greater than the integer 10:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def condition(x): return x > 10 print(condition(10))
# False print(condition(2))
# False print(condition(11))
# True
</pre>
<p>But you can also define more complicated conditions such as checking if they are prime numbers.</p>
<h3>Python List Count If</h3>
<p><strong>How can you count the elements of the list IF the condition is met?</strong></p>
<p>The answer is to use a simple <a rel="noreferrer noopener" href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" target="_blank">generator expression</a> <code>sum(condition(x) for x in lst)</code>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(condition(x) for x in lst)
2</pre>
<p>The result indicates that there are two elements that are larger than 10. You used a generator expression that returns an iterator of Booleans. Note that the Boolean <code>True</code> is represented by the integer value 1 and the Boolean <code>False</code> is represented by the integer value 0. That’s why you can simply calculate the sum over all Booleans to obtain the number of elements for which the condition holds. </p>
<h3>Python List Count Greater / Smaller Than</h3>
<p>If you want to determine the number of elements that are greater than or smaller than a specified value, just modify the condition in this example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(condition(x) for x in lst)
2</pre>
<p>For example, to find the number of elements smaller than 5, use the condition x&lt;5 in the generator expression:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst = [10, 11, 42, 1, 2, 3]
>>> sum(x&lt;5 for x in lst)
3</pre>
<h3>Python List Count Zero / Non-Zero</h3>
<p>To count the number of zeros in a given list, use the <code>list.count(0)</code> method call.</p>
<p>To count the number of non-zeros in a given list, you should use <em>conditional counting </em>as discussed before:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def condition(x): return x!=0 lst = [10, 11, 42, 1, 2, 0, 0, 0]
print(sum(condition(x) for x in lst))
# 5
</pre>
<h3>Python List Count Lambda + Map</h3>
<p>An alternative is to use a combination of the map and the lambda function. </p>
<p><strong>Related articles:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-get-rid-of-pythons-map-function-with-list-comprehension/" target="_blank">[Full Tutorial] Map Function</a>: manipulates each element in an iterable.</li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank">[Full Tutorial] Lambda Function</a>: creates an anonymous function.</li>
</ul>
<p>Here’s the code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> sum(map(lambda x: x%2==0, [1, 2, 3, 4, 5]))
2</pre>
<p>You count the number of even integers in the list. </p>
<ul>
<li>The lambda function returns a truth value for a given element <code>x</code>. </li>
<li>The map function transforms each list element into a Boolean value (1 or 0). </li>
<li>The sum function sums up the “1”s. </li>
</ul>
<p>The result is the number of elements for which the condition evaluates to <code>True</code>.</p>
<h2>Python List Count Regex / Count Matches</h2>
<p>Given a list of strings. How can you check how many list elements match a certain regex pattern? <a rel="noreferrer noopener" href="https://blog.finxter.com/python-regex/" target="_blank">(If you need a refresher on Python regular expressions, check out my ultimate guide on this blo</a><a href="https://blog.finxter.com/python-regex/" target="_blank" rel="noreferrer noopener">g</a><a rel="noreferrer noopener" href="https://blog.finxter.com/python-regex/" target="_blank"> – it’s really ultimate!)</a></p>
<ul>
<li>List <code>lst</code> of string elements</li>
<li>Pattern <code>p</code> to be matched against the strings in the list.</li>
</ul>
<p><strong>Solution</strong>: Use the concept of generator expressions with the ternary operator. </p>
<p><strong>Related articles:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/if-then-else-in-one-line-python/" target="_blank">Master ternary operator.</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">Master list comprehension.</a></li>
</ul>
<p>Here’s the code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import re
>>> p = 'a...e'
>>> lst = ['annie', 'alice', 'apex']
>>> sum(1 if re.match(p, x) else 0 for x in lst)
2</pre>
<h2>Python List Count Wildcard</h2>
<p>Do you want to count all string occurrences of a given prefix (e.g. prefix <code>"Sus"</code> for strings <code>"Susie"</code>, <code>"Susy"</code>, <code>"Susi"</code>)?</p>
<p><strong>Solution</strong>: Again you can use the concept of generator expressions with the ternary operator. </p>
<p><strong>Related articles:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/if-then-else-in-one-line-python/" target="_blank">Master ternary operator.</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">Master list comprehension.</a></li>
</ul>
<p>Here’s the code for this one using the wildcard operator in a pattern to count all occurrences of this pattern in the list.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> import re
>>> lst = ['Susi', 'Ann', 'Susanne', 'Susy']
>>> pattern = 'Sus.*'
>>> frequency = sum(1 if re.match(pattern, x) else 0 for x in lst)
>>> print(frequency)
3</pre>
<p>The generator expression produces a bunch of 1s and 0s—the former if the list element starts with prefix <code>'Sus'</code> and the latter if it doesn’t. By summing over all elements, you get the number of matches of the wildcard operator.</p>
<h2>Python List Count Not Working</h2>
<p>The <code>list.count(value)</code> method is very hard to break. Look what I tried to get an error:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst = [1, 1, 1, 2, 2, 3]
>>> lst.count(1)
3
>>> lst.count(2, 2)
Traceback (most recent call last): File "&lt;pyshell#19>", line 1, in &lt;module> lst.count(2, 2)
TypeError: count() takes exactly one argument (2 given)
>>> lst.count(4)
0
>>> lst.count("1")
0
>>> count(lst)
Traceback (most recent call last): File "&lt;pyshell#22>", line 1, in &lt;module> count(lst)
NameError: name 'count' is not defined
>>> </pre>
<p>You have to try really hard to break it. Just consider these tips:</p>
<ul>
<li>The <code>list.count(value)</code> method takes exactly one argument: the value you want to count. If you define more or less arguments, there will be an error.</li>
<li>The <code>list.count(value)</code> method is just that: a method of a list object. You need to call it on a list object. If you try to call it on another object, it will probably fail. If you try to use it just like that (without the list prefix, i.e., <code>count(value)</code>), it will also fail.</li>
<li>The <code>list.count(value)</code> will return 0 if you put in any object as an argument that does not evaluate to <code>True</code> when compared to the list elements using the <code>==</code> comparison operator. So make sure that the object you want to count really evaluates to <code>True</code> if you compare it against some list elements. You may assume this but it could easily fail to do so.</li>
</ul>
<h2>Python List Reference Count</h2>
<p>The <a rel="noreferrer noopener" href="https://docs.python.org/3.6/library/gc.html" target="_blank">Python garbage collector</a> keeps track of the number of times each object in memory is referenced. You call this “reference counting”. All objects that have reference count of zero cannot be reached by your code and, thus, can be safely removed by the garbage collector.</p>
<p>It’s unrelated to Python lists with the one exception: each list element increases the reference count by one because a list really is an array of pointers to the list objects in memory in the cPython implementation. </p>
<h2>Python List Count Tuples</h2>
<p><strong>How can you count the number of times a given tuple appears in a list?</strong></p>
<p>Simply use the tuple as the input argument value for the <code>list.count(value)</code> method. Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst = [(1, 2), (1, 1), 99, "Alice", True, (1, 1)]
>>> lst.count((1, 1))
2</pre>
<p><strong>How can you count the number of tuples in a given list? </strong></p>
<p>Use the <code>type(x)</code> method to check the type of a given variable <code>x</code>. Then compare the result with your desired data type (e.g. <code>tuple</code>). </p>
<p>Here’s an example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> sum(type(x)==tuple for x in lst)
3</pre>
<p><strong>Related articles:</strong></p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/if-then-else-in-one-line-python/" target="_blank">Master ternary operator.</a></li>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">Master list comprehension.</a></li>
</ul>
<h2>Python List Count and Sort</h2>
<p><strong>Given</strong>: list <code>lst</code>.</p>
<p><strong>Problem</strong>: You want to count the number of occurrences of all values in the list and sort them by their frequency.</p>
<p><strong>Example</strong>: for list elements [1, 1, 1, 1, 0, 0, 3, 1, 1, 3, 3, 3] you want to obtain their frequencies in a sorted manner:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">6 times --> element 1
4 times --> element 3
2 times --> element 0</pre>
<p><strong>Solution</strong>: Use the <code>collections.Counter(lst).most_common()</code> method that does exactly that. You can find the documentation <a rel="noreferrer noopener" href="https://docs.python.org/3/library/collections.html#collections.Counter" target="_blank">here</a>. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import collections lst = [3, 2, 1, 1, 1, 2, 2, 3]
print(collections.Counter(lst).most_common())</pre>
<p>Generates output:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[(2, 3), (1, 3), (3, 2)]</pre>
<h2>Python List Count Slow</h2>
<p>Do you want to improve performance of the <code>list.count(value)</code> method? It’s not easy because the runtime complexity is O(n) with n list elements.</p>
<p>There’s not much you can do about it. Of course, if you need to count the same element multiple times, you can use a cache dictionary to store its result. But this works only if the list has not changed. </p>
<p>You can also sort the list once which takes O(n log n) for n list elements. After that, you can call the implement a count method based on <a rel="noreferrer noopener" href="https://blog.finxter.com/iterative-vs-recursive-binary-search-algorithms-in-python/" target="_blank">binary search with </a>O(log n) runtime complexity. But if you need to count only a single element, this is not effective. </p>
<p>Interestingly, counting <em>all </em>elements in a list also has O(n) runtime complexity. Why? Because you’ll go over each element and add it to a dictionary if it doesn’t exist already (mapping the element to its counter value, initially 1). If it exists, you simply increment the counter by one. </p>
<p>In <a rel="noreferrer noopener" href="https://gist.github.com/treyhunner/0987601f960a5617a1be" target="_blank">this</a> excellent benchmark, you can find the performance of different counting methods. The <a rel="noreferrer noopener" href="https://docs.python.org/3/library/collections.html#collections.Counter" target="_blank">Counter </a>class seems to have best performance.</p>
<h2>Python List Count vs Len</h2>
<p><strong>What’s the difference?</strong></p>
<ul>
<li><strong>The <code>list.count(x)</code> method counts the number of occurrences of the element <code>x</code> in the <code>list</code>.</strong></li>
<li><strong>The <code>len(list)</code> method returns the total number of elements in the list.</strong></li>
</ul>
<p>Here’s a minimal example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> lst = [1, 2, 2, 2, 2]
>>> lst.count(2)
4
>>> len(lst)
5</pre>
<h2>Python List count() Thread Safe</h2>
<p>Do you have multiple threads that access your list at the same time? Then you need to be sure that the list operations (such as <code>count()</code>) are actually <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Thread_safety" target="_blank">thread safe</a>. </p>
<p>In other words: can you call the <code><code>count</code>()</code> operation in two threads on the same list at the same time? (And can you be sure that the result is meaningful?)</p>
<p>The answer is yes (if you use the <a rel="noreferrer noopener" href="https://github.com/python/cpython" target="_blank">cPython </a>implementation). The reason is Python’s <a rel="noreferrer noopener" href="https://wiki.python.org/moin/GlobalInterpreterLock" target="_blank">global interpreter lock</a> that ensures that a thread that’s currently working on its code will first finish its current basic Python operation as defined by the cPython implementation. Only if it terminates with this operation will the next thread be able to access the computational resource. This is ensured with a sophisticated locking scheme by the cPython implementation. </p>
<p>The only thing you need to know is that each basic operation in the cPython implementation is <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Atomicity_(database_systems)" target="_blank">atomic</a>. It’s executed wholly and at once before any other thread has the chance to run on the same virtual engine. Therefore, there are no race conditions. An example of such a race condition would be the following: the first thread reads a value from the list, the second thread overwrites the value, and the first thread overwrites the value again invalidating the second thread’s operation.</p>
<p><strong>All cPython operations are thread-safe. </strong>But if you combine those operations into higher-level functions, those are not generally thread safe as they consist of many (possibly interleaving) operations.</p>
<h2>Where to Go From Here?</h2>
<p><strong>The <code>list.count(x)</code> method counts the number of times the element <code>x</code> appears in the <code>list</code>. </strong></p>
<p>You’ve learned the ins and outs of this important <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-methods/" target="_blank">Python list method</a>.</p>
<p>If you keep struggling with those basic Python commands and you feel stuck in your learning progress, I’ve got something for you: <a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">Python One-Liners</a> (Amazon Link). </p>
<p>In the book, I’ll give you a thorough overview of critical computer science topics such as machine learning, regular expression, data science, NumPy, and Python basics—all in a single line of Python code!</p>
<p><a rel="noreferrer noopener" href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank">Get the book from Amazon!</a></p>
<p><strong>OFFICIAL BOOK DESCRIPTION:</strong> <em>Python One-Liners will show readers how to perform useful tasks with one line of Python code. Following a brief Python refresher, the book covers essential advanced topics like slicing, list comprehension, broadcasting, lambda functions, algorithms, regular expressions, neural networks, logistic regression and more. Each of the 50 book sections introduces a problem to solve, walks the reader through the skills necessary to solve that problem, then provides a concise one-liner Python solution with a detailed explanation.</em></p>
</div>


https://www.sickgaming.net/blog/2020/03/...ist-index/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016