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 heapq.nlargest() 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.
How the example above works
The function findKLargest sorts the list in descending order with arr.sort(reverse=True). It then loops over the first k positions and prints each value on the same line, because end=" " replaces the default newline with a space. With the sample input [1, 23, 12, 9, 30, 2, 50] and k = 3, the sorted list is [50, 30, 23, 12, 9, 2, 1], so the program prints the first three values.
$ python3 findKLargestinArray.py
50 30 23 $
The shell prompt appears right after the output because the program never prints a final newline. The stated complexity is correct: Python's sort (Timsort) is O(N log N), and printing k items adds O(k). The comment calls this "efficient", 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.
Problems with the original and a corrected version
The original code is correct for the sample input, but it has several issues that matter in real code and in interviews:
- It mutates the caller's list.
arr.sort()sorts in place, so the caller's original order is lost after the call. - It crashes when
kis larger than the list.arr[i]raisesIndexError: list index out of rangewhenireacheslen(arr). - It prints instead of returning. Other code cannot reuse or test a function that only prints.
- No trailing newline. Any output that follows ends up on the same line.
- Naming. PEP 8 recommends
snake_casefor function names, sofind_k_largestis the conventional spelling.
def find_k_largest(arr, k):
"""Return the k largest elements of arr in descending order.
The input list is not modified. If k is larger than the list,
all elements are returned. If k <= 0, an empty list is returned.
"""
if k <= 0:
return []
return sorted(arr, reverse=True)[:k]
if __name__ == "__main__":
arr = [1, 23, 12, 9, 30, 2, 50]
k = 3
result = find_k_largest(arr, k)
print(*result) # 50 30 23
print(arr) # [1, 23, 12, 9, 30, 2, 50] - unchangedCode language: PHP (php)
sorted() returns a new list, so the input stays unchanged. Slicing never raises IndexError: [:k] returns the whole list when k is larger than its length. print(*result) unpacks the list into separate arguments, so the values are separated by spaces and followed by a newline. The if __name__ == "__main__": guard stops the demo from running when another module imports the function.
Using heapq.nlargest from the standard library
In most production code, heapq.nlargest() 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.
import heapq
arr = [1, 23, 12, 9, 30, 2, 50]
print(heapq.nlargest(3, arr)) # [50, 30, 23]
# Works with a key function, like sorted()
servers = [
{"host": "web-1", "cpu": 71},
{"host": "web-2", "cpu": 93},
{"host": "db-1", "cpu": 88},
]
top_two = heapq.nlargest(2, servers, key=lambda s: s["cpu"])
print([s["host"] for s in top_two]) # ['web-2', 'db-1']Code language: PHP (php)
Note: The Python documentation says nlargest() works best for small values of n. When n is close to the size of the input, sorted(...)[:n] is usually faster, and for n == 1 the built-in max() is the better choice.
Writing a size-k min-heap by hand
Interviewers often ask you to implement the heap approach yourself. The idea is to keep the k largest values seen so far in a min-heap. The smallest of those k values sits at heap[0]. If a new element is larger than heap[0], it replaces the smallest one. Otherwise it cannot be among the k largest and is skipped.
import heapq
def k_largest_min_heap(arr, k):
if k <= 0:
return []
heap = list(arr[:k]) # first k elements (fewer if arr is short)
heapq.heapify(heap) # O(k)
for x in arr[k:]: # remaining N - k elements
if x > heap[0]: # larger than the smallest of the current top k
heapq.heapreplace(heap, x) # pop smallest, push x: O(log k)
return sorted(heap, reverse=True) # O(k log k) for ordered output
print(k_largest_min_heap([1, 23, 12, 9, 30, 2, 50], 3)) # [50, 30, 23]Code language: PHP (php)
The total cost is O(k + (N โ k) log k + k log k), which is O(N log k), with O(k) extra memory. heapreplace() does the pop and the push in one operation, which is cheaper than calling heappop() and then heappush().
Quickselect for average linear time
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ยฒ), and a random pivot makes that case very unlikely. The three-way split below handles duplicate values correctly.
import random
def k_largest_quickselect(items, k):
"""Return the k largest elements (unordered). Average O(N)."""
if k <= 0:
return []
if k >= len(items):
return list(items)
pivot = random.choice(items)
greater = [x for x in items if x > pivot]
if k <= len(greater):
return k_largest_quickselect(greater, k)
equal = [x for x in items if x == pivot]
if k <= len(greater) + len(equal):
return greater + equal[:k - len(greater)]
less = [x for x in items if x < pivot]
return greater + equal + k_largest_quickselect(less, k - len(greater) - len(equal))
result = k_largest_quickselect([1, 23, 12, 9, 30, 2, 50], 3)
print(sorted(result, reverse=True)) # [50, 30, 23]Code language: PHP (php)
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, heapq.nlargest() is often just as fast in practice because its core is implemented in C. Measure before you choose.
NumPy for large numeric arrays
If the data is already in a NumPy array, use numpy.partition(). It runs a selection algorithm in compiled code and places the k largest values in the last k positions, in no guaranteed order.
import numpy as np
a = np.array([1, 23, 12, 9, 30, 2, 50])
k = 3
top_k = np.partition(a, -k)[-k:] # k largest, unordered
print(np.sort(top_k)[::-1]) # [50 30 23]
# Indices instead of values
idx = np.argpartition(a, -k)[-k:]
print(idx[np.argsort(a[idx])[::-1]]) # [6 4 1]Code language: PHP (php)
Note: np.partition(a, -k) raises a ValueError if k 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.
Choosing an approach
| Approach | Time | Extra space | Output order | Best for |
|---|---|---|---|---|
sorted(arr, reverse=True)[:k] | O(N log N) | O(N) | Descending | Simple code, or k close to N |
heapq.nlargest(k, arr) | O(N log k) | O(k) | Descending | Default choice, streams, small k |
| Manual min-heap | O(N log k) | O(k) | Descending after final sort | Interviews, custom logic |
| Quickselect | O(N) average, O(Nยฒ) worst | O(N) as written | Unordered | Very large N when only membership matters |
numpy.partition | O(N) on average | O(N) | Unordered | Numeric data already in NumPy |
Relative speed depends on N, k, your data and your Python version. To compare approaches on your own data, use timeit:
python3 -m timeit -s "import random, heapq; a=[random.random() for _ in range(1_000_000)]" "heapq.nlargest(10, a)"
python3 -m timeit -s "import random; a=[random.random() for _ in range(1_000_000)]" "sorted(a, reverse=True)[:10]"Code language: JavaScript (javascript)
Testing edge cases and common errors
Each implementation should pass the same set of edge cases. These assertions work with find_k_largest, and with the other functions after you sort their output:
def test_find_k_largest():
assert find_k_largest([1, 23, 12, 9, 30, 2, 50], 3) == [50, 30, 23]
assert find_k_largest([5, 1, 5, 3], 2) == [5, 5] # duplicates kept
assert find_k_largest([4, 2], 10) == [4, 2] # k > len
assert find_k_largest([4, 2], 0) == [] # k == 0
assert find_k_largest([], 3) == [] # empty input
assert find_k_largest([-3, -1, -2], 1) == [-1] # negatives
test_find_k_largest()
print("all tests passed")Code language: PHP (php)
IndexError: list index out of range: this is the original loop withk > len(arr). Use slicing ormin(k, len(arr)).- Wrong order with input from
input(): values read as strings sort alphabetically, so"9"ranks above"50". Convert them first witharr = list(map(int, input().split())). TypeError: '<' not supported between instances of 'str' and 'int': Python 3 cannot compare mixed types. Clean the data or pass akeyfunction.- Duplicates in the result:
[5, 5]counts as two of the largest elements. If you need distinct values, deduplicate first withheapq.nlargest(k, set(arr)).
Frequently asked questions
What is the fastest way to get the k largest elements in Python?
In most cases, use heapq.nlargest(k, data), which runs in about O(N log k) and keeps only k items in memory. When k is close to N, sorted(data, reverse=True)[:k] is usually faster. For numeric NumPy arrays, np.partition is the fastest option.
How do I find the k largest elements without changing the original list?
Use sorted() or heapq.nlargest(). Both return a new list. list.sort() sorts the list in place and destroys the original order, which is what the example above does.
Is a min-heap or a max-heap used for the k largest elements?
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 heap[0]. A max-heap of all N elements also works, but it uses O(N) memory.
How do I get the indices of the k largest elements?
For a list, use heapq.nlargest(k, range(len(arr)), key=arr.__getitem__). For a NumPy array, use np.argpartition(a, -k)[-k:] and then sort those indices by their values if you need them ranked.
What is the time complexity of the original sorting approach?
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.
Related tutorials
- More Python tutorials
- TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-
- Top 50 Python Interview Questions and Answers
- What is Pandas and use cases of Pandas?
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals