
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python - Inserting item in sorted list maintaining order
In this article, we are going to learn how to insert an item in a sorted list maintaining the order. Python has a built-in module called bisect that helps us to insert any element in an appropriate position in the list.
Follow the below steps to write the code.
- Import the module bisect.
- Initialize list and element that need to insert
- The module bisect has a method called insort that inserts an element into a list in an appropriate position. Use the method and insert the element.
- Print the list.
Example
# importing the module import bisect # initializing the list, element numbers = [10, 23, 27, 32] element = 25 # inserting element using bisect.insort(list, element) bisect.insort(numbers, element) # printing the list print(numbers)
If you run the above code, then you will get the following result.
Output
[10, 23, 25, 27, 32]
Conclusion
We can iterate over the list and find the position to insert an element into the correct position. That's not an efficient way to do it. The insort method handles it more efficiently.
- Related Articles
- Program to find squared elements list in sorted order in Python
- Maintaining order in MySQL “IN” query?
- Program to merge two sorted list to form larger sorted list in Python
- Python - Combine two lists by maintaining duplicates in first list
- Python - Get items in sorted order from given dictionary
- What is the best way to search for an item in a sorted list in JavaScript?
- How to generate a sorted list in Python?
- To print all elements in sorted order from row and column wise sorted matrix in Python
- Convert list of string into sorted list of integer in Python
- Square list of elements in sorted form in Python
- Check if list is sorted or not in Python
- Why doesn’t list.sort() return the sorted list in Python?
- How to restrict inserting an item with the same name in MongoDB?
- Inserting a new interval in a sorted array of intervals in JavaScript
- Find missing numbers in a sorted list range in Python

Advertisements