
- 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 program to insert an element into sorted list
In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a list, we need to insert an element in a list without changing sorted order
There are two approaches as discussed below−
Approach 1: The brute-force method
Example
def insert(list_, n): # search for i in range(len(list_)): if list_[i] > n: index = i break # Insertion list_ = list_[:i] + [n] + list_[i:] return list_ # Driver function list_ = ['t','u','t','o','r'] n = 'e' print(insert(list_, n))
Output
['e', 't', 'u', 't', 'o', 'r']
Approach 2: Using the bisect module
Example
#built-in bisect module import bisect def insert(list_, n): bisect.insort(list_, n) return list_ list_ = ['t','u','t','o','r'] n = 'e' print(insert(list_, n))
Output
['e', 't', 'u', 't', 'o', 'r']
All the variables are declared in the local scope and their references are seen in the figure above.
Conclusion
In this article, we have learned about how we can insert an element in a sorted list.
- Related Articles
- Program to find index, where we can insert element to keep list sorted in Python
- Program to insert new element into a linked list before the given position in Python
- Insert into a Sorted Circular Linked List in C++
- Program to find one minimum possible interval to insert into an interval list in Python
- Program to merge two sorted list to form larger sorted list in Python
- Golang Program to insert an element into the array at the specified index
- How to insert an element into DOM using jQuery?
- Insert an element to List using ListIterator in Java
- Convert list of string into sorted list of integer in Python
- C Program to insert an array element using pointers.
- How to insert an item into a C# list by using an index?
- Python program to create a sorted merged list of two unsorted list
- Insert an element into Collection at specified index in C#
- Python program to search an element in a Circular Linked List
- Python program to search an element in a doubly linked list

Advertisements