Python heapq module

I use a module heapqto determine the smallest item in a list.

I have this code below, but the return value heapq.heapify()is None.

How to get the result in a new list?

>>> a=heapq.heapify(lista)
>>> a
>>> lista=[1,2,3,4,5]
>>> a=heapq.heapify(lista)
>>> print(a)
None
+5
source share
1 answer

heapq.heapifyreturns nothing, it checks the list in place; this is much more efficient for this:

>>> import heapq
>>> lista = [44, 42, 3, 89, 10]
>>> heapq.heapify(lista)
>>> lista
[3, 10, 44, 89, 42]

If you need a new list, create a copy:

>>> lista = [44, 42, 3, 89, 10]
>>> newlist = lista[:]
>>> heapq.heapify(newlist)
>>> lista
[44, 42, 3, 89, 10]
>>> newlist
[3, 10, 44, 89, 42]

This, of course, defeats the goal, since copying the list also has a (linear) cost.

If you need the smallest item in the list, the function will be as fast, if you find only one smallest element (as well as scans input list once, so O (n) cost): min()heapify()min()

>>> min(lista)
3

, heapq, . , , . python nsmallest, .

+9

All Articles