{"id":31986,"date":"2026-12-01T22:04:27","date_gmt":"2026-12-01T22:04:27","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=31986"},"modified":"2026-12-01T22:04:27","modified_gmt":"2026-12-01T22:04:27","slug":"python-example-code-program-for-printing-k-largest-elements-in-an-array","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/python-example-code-program-for-printing-k-largest-elements-in-an-array\/","title":{"rendered":"Python Example Code: Program for printing k largest elements in an array"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">To print the k largest elements of a Python list, you can sort it in descending order and take the first k items. That is what the example below does. For large inputs, a heap with <code>heapq.nlargest()<\/code> or a quickselect partition is faster. This tutorial explains the original code, fixes its edge-case bugs and compares the sort, heap, quickselect and NumPy approaches, with complexity notes and tests.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<script src=\"https:\/\/gist.github.com\/devops-school\/f9b3be8a372e1aa0e971f46ff507f774.js\"><\/script>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How the example above works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The function <code>findKLargest<\/code> sorts the list in descending order with <code>arr.sort(reverse=True)<\/code>. It then loops over the first <code>k<\/code> positions and prints each value on the same line, because <code>end=&quot; &quot;<\/code> replaces the default newline with a space. With the sample input <code>[1, 23, 12, 9, 30, 2, 50]<\/code> and <code>k = 3<\/code>, the sorted list is <code>[50, 30, 23, 12, 9, 2, 1]<\/code>, so the program prints the first three values.<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">$ python3 findKLargestinArray.py\n50 30 23 $<\/code><\/span><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The shell prompt appears right after the output because the program never prints a final newline. The stated complexity is correct: Python&#039;s sort (Timsort) is O(N log N), and printing k items adds O(k). The comment calls this &quot;efficient&quot;, but sorting the whole list is more work than needed when k is much smaller than N. The heap and quickselect versions below avoid that extra work.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Problems with the original and a corrected version<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The original code is correct for the sample input, but it has several issues that matter in real code and in interviews:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>It mutates the caller&#039;s list.<\/strong> <code>arr.sort()<\/code> sorts in place, so the caller&#039;s original order is lost after the call.<\/li>\n\n\n<li><strong>It crashes when <code>k<\/code> is larger than the list.<\/strong> <code>arr[i]<\/code> raises <code>IndexError: list index out of range<\/code> when <code>i<\/code> reaches <code>len(arr)<\/code>.<\/li>\n\n\n<li><strong>It prints instead of returning.<\/strong> Other code cannot reuse or test a function that only prints.<\/li>\n\n\n<li><strong>No trailing newline.<\/strong> Any output that follows ends up on the same line.<\/li>\n\n\n<li><strong>Naming.<\/strong> PEP 8 recommends <code>snake_case<\/code> for function names, so <code>find_k_largest<\/code> is the conventional spelling.<\/li>\n<\/ul>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">def find_k_largest(arr, k):\n    <span class=\"hljs-string\">\"\"<\/span><span class=\"hljs-string\">\"Return the k largest elements of arr in descending order.\n\n    The input list is not modified. If k is larger than the list,\n    all elements are returned. If k &lt;= 0, an empty list is returned.\n    \"<\/span><span class=\"hljs-string\">\"\"<\/span>\n    <span class=\"hljs-keyword\">if<\/span> k &lt;= <span class=\"hljs-number\">0<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> &#91;]\n    <span class=\"hljs-keyword\">return<\/span> sorted(arr, reverse=<span class=\"hljs-keyword\">True<\/span>)&#91;:k]\n\n\n<span class=\"hljs-keyword\">if<\/span> __name__ == <span class=\"hljs-string\">\"__main__\"<\/span>:\n    arr = &#91;<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">23<\/span>, <span class=\"hljs-number\">12<\/span>, <span class=\"hljs-number\">9<\/span>, <span class=\"hljs-number\">30<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">50<\/span>]\n    k = <span class=\"hljs-number\">3<\/span>\n    result = find_k_largest(arr, k)\n    <span class=\"hljs-keyword\">print<\/span>(*result)          <span class=\"hljs-comment\"># 50 30 23<\/span>\n    <span class=\"hljs-keyword\">print<\/span>(arr)              <span class=\"hljs-comment\"># &#91;1, 23, 12, 9, 30, 2, 50] - unchanged<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><code>sorted()<\/code> returns a new list, so the input stays unchanged. Slicing never raises <code>IndexError<\/code>: <code>[:k]<\/code> returns the whole list when <code>k<\/code> is larger than its length. <code>print(*result)<\/code> unpacks the list into separate arguments, so the values are separated by spaces and followed by a newline. The <code>if __name__ == &quot;__main__&quot;:<\/code> guard stops the demo from running when another module imports the function.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using heapq.nlargest from the standard library<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In most production code, <code>heapq.nlargest()<\/code> is the right choice. It keeps a heap of only k items while it scans the input, so it runs in about O(N log k) time and O(k) extra memory. The result is already in descending order. It also accepts any iterable, including generators and file lines, so the data does not need to fit in a list first.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import heapq\n\narr = &#91;<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">23<\/span>, <span class=\"hljs-number\">12<\/span>, <span class=\"hljs-number\">9<\/span>, <span class=\"hljs-number\">30<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">50<\/span>]\n<span class=\"hljs-keyword\">print<\/span>(heapq.nlargest(<span class=\"hljs-number\">3<\/span>, arr))          <span class=\"hljs-comment\"># &#91;50, 30, 23]<\/span>\n\n<span class=\"hljs-comment\"># Works with a key function, like sorted()<\/span>\nservers = &#91;\n    {<span class=\"hljs-string\">\"host\"<\/span>: <span class=\"hljs-string\">\"web-1\"<\/span>, <span class=\"hljs-string\">\"cpu\"<\/span>: <span class=\"hljs-number\">71<\/span>},\n    {<span class=\"hljs-string\">\"host\"<\/span>: <span class=\"hljs-string\">\"web-2\"<\/span>, <span class=\"hljs-string\">\"cpu\"<\/span>: <span class=\"hljs-number\">93<\/span>},\n    {<span class=\"hljs-string\">\"host\"<\/span>: <span class=\"hljs-string\">\"db-1\"<\/span>, <span class=\"hljs-string\">\"cpu\"<\/span>: <span class=\"hljs-number\">88<\/span>},\n]\ntop_two = heapq.nlargest(<span class=\"hljs-number\">2<\/span>, servers, key=lambda s: s&#91;<span class=\"hljs-string\">\"cpu\"<\/span>])\n<span class=\"hljs-keyword\">print<\/span>(&#91;s&#91;<span class=\"hljs-string\">\"host\"<\/span>] <span class=\"hljs-keyword\">for<\/span> s in top_two])    <span class=\"hljs-comment\"># &#91;'web-2', 'db-1']<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> The Python documentation says <code>nlargest()<\/code> works best for small values of n. When n is close to the size of the input, <code>sorted(...)[:n]<\/code> is usually faster, and for n == 1 the built-in <code>max()<\/code> is the better choice.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Writing a size-k min-heap by hand<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Interviewers often ask you to implement the heap approach yourself. The idea is to keep the k largest values seen so far in a <strong>min-heap<\/strong>. The smallest of those k values sits at <code>heap[0]<\/code>. If a new element is larger than <code>heap[0]<\/code>, it replaces the smallest one. Otherwise it cannot be among the k largest and is skipped.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import heapq\n\ndef k_largest_min_heap(arr, k):\n    <span class=\"hljs-keyword\">if<\/span> k &lt;= <span class=\"hljs-number\">0<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> &#91;]\n    heap = <span class=\"hljs-keyword\">list<\/span>(arr&#91;:k])        <span class=\"hljs-comment\"># first k elements (fewer if arr is short)<\/span>\n    heapq.heapify(heap)         <span class=\"hljs-comment\"># O(k)<\/span>\n    <span class=\"hljs-keyword\">for<\/span> x in arr&#91;k:]:           <span class=\"hljs-comment\"># remaining N - k elements<\/span>\n        <span class=\"hljs-keyword\">if<\/span> x &gt; heap&#91;<span class=\"hljs-number\">0<\/span>]:         <span class=\"hljs-comment\"># larger than the smallest of the current top k<\/span>\n            heapq.heapreplace(heap, x)   <span class=\"hljs-comment\"># pop smallest, push x: O(log k)<\/span>\n    <span class=\"hljs-keyword\">return<\/span> sorted(heap, reverse=<span class=\"hljs-keyword\">True<\/span>)    <span class=\"hljs-comment\"># O(k log k) for ordered output<\/span>\n\n<span class=\"hljs-keyword\">print<\/span>(k_largest_min_heap(&#91;<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">23<\/span>, <span class=\"hljs-number\">12<\/span>, <span class=\"hljs-number\">9<\/span>, <span class=\"hljs-number\">30<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">50<\/span>], <span class=\"hljs-number\">3<\/span>))   <span class=\"hljs-comment\"># &#91;50, 30, 23]<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The total cost is O(k + (N \u2212 k) log k + k log k), which is O(N log k), with O(k) extra memory. <code>heapreplace()<\/code> does the pop and the push in one operation, which is cheaper than calling <code>heappop()<\/code> and then <code>heappush()<\/code>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Quickselect for average linear time<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Quickselect uses the partition step from quicksort. Pick a pivot, split the values into those greater than, equal to and less than the pivot, then recurse only into the part that still contains the k-th largest value. Its average cost is O(N). The worst case is O(N\u00b2), and a random pivot makes that case very unlikely. The three-way split below handles duplicate values correctly.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import random\n\ndef k_largest_quickselect(items, k):\n    <span class=\"hljs-string\">\"\"<\/span><span class=\"hljs-string\">\"Return the k largest elements (unordered). Average O(N).\"<\/span><span class=\"hljs-string\">\"\"<\/span>\n    <span class=\"hljs-keyword\">if<\/span> k &lt;= <span class=\"hljs-number\">0<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> &#91;]\n    <span class=\"hljs-keyword\">if<\/span> k &gt;= len(items):\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">list<\/span>(items)\n    pivot = random.choice(items)\n    greater = &#91;x <span class=\"hljs-keyword\">for<\/span> x in items <span class=\"hljs-keyword\">if<\/span> x &gt; pivot]\n    <span class=\"hljs-keyword\">if<\/span> k &lt;= len(greater):\n        <span class=\"hljs-keyword\">return<\/span> k_largest_quickselect(greater, k)\n    equal = &#91;x <span class=\"hljs-keyword\">for<\/span> x in items <span class=\"hljs-keyword\">if<\/span> x == pivot]\n    <span class=\"hljs-keyword\">if<\/span> k &lt;= len(greater) + len(equal):\n        <span class=\"hljs-keyword\">return<\/span> greater + equal&#91;:k - len(greater)]\n    less = &#91;x <span class=\"hljs-keyword\">for<\/span> x in items <span class=\"hljs-keyword\">if<\/span> x &lt; pivot]\n    <span class=\"hljs-keyword\">return<\/span> greater + equal + k_largest_quickselect(less, k - len(greater) - len(equal))\n\nresult = k_largest_quickselect(&#91;<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">23<\/span>, <span class=\"hljs-number\">12<\/span>, <span class=\"hljs-number\">9<\/span>, <span class=\"hljs-number\">30<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">50<\/span>], <span class=\"hljs-number\">3<\/span>)\n<span class=\"hljs-keyword\">print<\/span>(sorted(result, reverse=<span class=\"hljs-keyword\">True<\/span>))   <span class=\"hljs-comment\"># &#91;50, 30, 23]<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\">The function returns the k largest values in no particular order. If you need them ranked, sort the result afterwards, which adds O(k log k). This list-building version is easy to read but uses O(N) extra memory. An in-place Lomuto or Hoare partition uses less memory but is more code. In pure Python, <code>heapq.nlargest()<\/code> is often just as fast in practice because its core is implemented in C. Measure before you choose.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">NumPy for large numeric arrays<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If the data is already in a NumPy array, use <code>numpy.partition()<\/code>. It runs a selection algorithm in compiled code and places the k largest values in the last k positions, in no guaranteed order.<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">import numpy <span class=\"hljs-keyword\">as<\/span> np\n\na = np.<span class=\"hljs-keyword\">array<\/span>(&#91;<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">23<\/span>, <span class=\"hljs-number\">12<\/span>, <span class=\"hljs-number\">9<\/span>, <span class=\"hljs-number\">30<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">50<\/span>])\nk = <span class=\"hljs-number\">3<\/span>\ntop_k = np.partition(a, -k)&#91;-k:]        <span class=\"hljs-comment\"># k largest, unordered<\/span>\n<span class=\"hljs-keyword\">print<\/span>(np.sort(top_k)&#91;::<span class=\"hljs-number\">-1<\/span>])             <span class=\"hljs-comment\"># &#91;50 30 23]<\/span>\n\n<span class=\"hljs-comment\"># Indices instead of values<\/span>\nidx = np.argpartition(a, -k)&#91;-k:]\n<span class=\"hljs-keyword\">print<\/span>(idx&#91;np.argsort(a&#91;idx])&#91;::<span class=\"hljs-number\">-1<\/span>]])    <span class=\"hljs-comment\"># &#91;6 4 1]<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p class=\"wp-block-paragraph\"><strong>Note:<\/strong> <code>np.partition(a, -k)<\/code> raises a <code>ValueError<\/code> if <code>k<\/code> is larger than the array length, so check the bounds first. Converting a Python list to an array costs O(N), so NumPy only pays off when the data is already an array or is large.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Choosing an approach<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Approach<\/th><th>Time<\/th><th>Extra space<\/th><th>Output order<\/th><th>Best for<\/th><\/tr><\/thead><tbody><tr><td><code>sorted(arr, reverse=True)[:k]<\/code><\/td><td>O(N log N)<\/td><td>O(N)<\/td><td>Descending<\/td><td>Simple code, or k close to N<\/td><\/tr><tr><td><code>heapq.nlargest(k, arr)<\/code><\/td><td>O(N log k)<\/td><td>O(k)<\/td><td>Descending<\/td><td>Default choice, streams, small k<\/td><\/tr><tr><td>Manual min-heap<\/td><td>O(N log k)<\/td><td>O(k)<\/td><td>Descending after final sort<\/td><td>Interviews, custom logic<\/td><\/tr><tr><td>Quickselect<\/td><td>O(N) average, O(N\u00b2) worst<\/td><td>O(N) as written<\/td><td>Unordered<\/td><td>Very large N when only membership matters<\/td><\/tr><tr><td><code>numpy.partition<\/code><\/td><td>O(N) on average<\/td><td>O(N)<\/td><td>Unordered<\/td><td>Numeric data already in NumPy<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Relative speed depends on N, k, your data and your Python version. To compare approaches on your own data, use <code>timeit<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"JavaScript\" data-shcb-language-slug=\"javascript\"><span><code class=\"hljs language-javascript\">python3 -m timeit -s <span class=\"hljs-string\">\"import random, heapq; a=&#91;random.random() for _ in range(1_000_000)]\"<\/span> <span class=\"hljs-string\">\"heapq.nlargest(10, a)\"<\/span>\npython3 -m timeit -s <span class=\"hljs-string\">\"import random; a=&#91;random.random() for _ in range(1_000_000)]\"<\/span> <span class=\"hljs-string\">\"sorted(a, reverse=True)&#91;:10]\"<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">JavaScript<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">javascript<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Testing edge cases and common errors<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Each implementation should pass the same set of edge cases. These assertions work with <code>find_k_largest<\/code>, and with the other functions after you sort their output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\">def test_find_k_largest():\n    assert find_k_largest(&#91;<span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">23<\/span>, <span class=\"hljs-number\">12<\/span>, <span class=\"hljs-number\">9<\/span>, <span class=\"hljs-number\">30<\/span>, <span class=\"hljs-number\">2<\/span>, <span class=\"hljs-number\">50<\/span>], <span class=\"hljs-number\">3<\/span>) == &#91;<span class=\"hljs-number\">50<\/span>, <span class=\"hljs-number\">30<\/span>, <span class=\"hljs-number\">23<\/span>]\n    assert find_k_largest(&#91;<span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">1<\/span>, <span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">3<\/span>], <span class=\"hljs-number\">2<\/span>) == &#91;<span class=\"hljs-number\">5<\/span>, <span class=\"hljs-number\">5<\/span>]        <span class=\"hljs-comment\"># duplicates kept<\/span>\n    assert find_k_largest(&#91;<span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">2<\/span>], <span class=\"hljs-number\">10<\/span>) == &#91;<span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">2<\/span>]              <span class=\"hljs-comment\"># k &gt; len<\/span>\n    assert find_k_largest(&#91;<span class=\"hljs-number\">4<\/span>, <span class=\"hljs-number\">2<\/span>], <span class=\"hljs-number\">0<\/span>) == &#91;]                   <span class=\"hljs-comment\"># k == 0<\/span>\n    assert find_k_largest(&#91;], <span class=\"hljs-number\">3<\/span>) == &#91;]                       <span class=\"hljs-comment\"># empty input<\/span>\n    assert find_k_largest(&#91;<span class=\"hljs-number\">-3<\/span>, <span class=\"hljs-number\">-1<\/span>, <span class=\"hljs-number\">-2<\/span>], <span class=\"hljs-number\">1<\/span>) == &#91;<span class=\"hljs-number\">-1<\/span>]           <span class=\"hljs-comment\"># negatives<\/span>\n\ntest_find_k_largest()\n<span class=\"hljs-keyword\">print<\/span>(<span class=\"hljs-string\">\"all tests passed\"<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>IndexError: list index out of range<\/code><\/strong>: this is the original loop with <code>k &gt; len(arr)<\/code>. Use slicing or <code>min(k, len(arr))<\/code>.<\/li>\n\n\n<li><strong>Wrong order with input from <code>input()<\/code><\/strong>: values read as strings sort alphabetically, so <code>&quot;9&quot;<\/code> ranks above <code>&quot;50&quot;<\/code>. Convert them first with <code>arr = list(map(int, input().split()))<\/code>.<\/li>\n\n\n<li><strong><code>TypeError: &#039;&lt;&#039; not supported between instances of &#039;str&#039; and &#039;int&#039;<\/code><\/strong>: Python 3 cannot compare mixed types. Clean the data or pass a <code>key<\/code> function.<\/li>\n\n\n<li><strong>Duplicates in the result<\/strong>: <code>[5, 5]<\/code> counts as two of the largest elements. If you need distinct values, deduplicate first with <code>heapq.nlargest(k, set(arr))<\/code>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is the fastest way to get the k largest elements in Python?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In most cases, use <code>heapq.nlargest(k, data)<\/code>, which runs in about O(N log k) and keeps only k items in memory. When k is close to N, <code>sorted(data, reverse=True)[:k]<\/code> is usually faster. For numeric NumPy arrays, <code>np.partition<\/code> is the fastest option.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I find the k largest elements without changing the original list?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>sorted()<\/code> or <code>heapq.nlargest()<\/code>. Both return a new list. <code>list.sort()<\/code> sorts the list in place and destroys the original order, which is what the example above does.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is a min-heap or a max-heap used for the k largest elements?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use a min-heap of size k. Its root is the smallest of the current top k, so each new element needs only one comparison with <code>heap[0]<\/code>. A max-heap of all N elements also works, but it uses O(N) memory.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I get the indices of the k largest elements?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For a list, use <code>heapq.nlargest(k, range(len(arr)), key=arr.__getitem__)<\/code>. For a NumPy array, use <code>np.argpartition(a, -k)[-k:]<\/code> and then sort those indices by their values if you need them ranked.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the time complexity of the original sorting approach?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It is O(N log N) for the sort plus O(k) for printing, which is O(N log N) overall. It also needs no extra memory beyond the in-place sort, but it modifies the input list.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Related tutorials<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/category\/programming\/python-programming-scripting-languages\/\">More Python tutorials<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/top-100-interview-questions-for-python\/\">TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/top-50-python-interview-questions-and-answers\/\">Top 50 Python Interview Questions and Answers<\/a><\/li>\n\n\n<li><a href=\"https:\/\/www.devopsschool.com\/blog\/what-is-pandas-and-use-cases-of-pandas\/\">What is Pandas and use cases of Pandas?<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>To print the k largest elements of a Python list, you can sort it in descending order and take the first k items. That is what the&#8230; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[499],"tags":[6904,5432],"class_list":["post-31986","post","type-post","status-publish","format-standard","hentry","category-python-programming-scripting-languages","tag-algorithms","tag-arrays"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/31986","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=31986"}],"version-history":[{"count":3,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/31986\/revisions"}],"predecessor-version":[{"id":80497,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/31986\/revisions\/80497"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=31986"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=31986"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=31986"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}