Remove the smallest item and insert a replacement.
What You Will Learn
heapreplace(heap, item) always pops an existing item then pushes the replacement. Unlike heappushpop(), it requires a nonempty heap and can return a value larger than the new input.
Time complexity assumes a specific input structure. Include setup work such as sorting or building a lookup table when comparing complete solutions.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
import heapq
values = [3, 6, 8]
heapq.heapify(values)
print(heapq.heapreplace(values, 1))
print(values[0])
How the Example Works
- The imports provide the standard-library tools used in the demonstration: heapq.
- The variable values holds the result of [3, 6, 8]. Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
3
1
When You Would Use This
This technique matters when a program handles larger queues, sorted records, or repeated lookups. Choose the data structure based on actual operations and the preconditions the algorithm requires. Verify boundary inputs before optimizing for speed.
Practice: Modify the Code
Replace the highest-priority completed task with a new pending task.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Calling heapreplace() on an empty heap, which raises IndexError.
- Overlooking this documented constraint: unlike heappushpop(), it requires a nonempty heap and can return a value larger than the new input.
Key Takeaways
- Remove the smallest item and insert a replacement.
- heapreplace(heap, item) always pops an existing item then pushes the replacement.
- Apply this operation only after checking the assumptions and input conditions shown in the example.