Given a sorted list and an element, Write a Python program to insert the element into the given list in sorted position.
Input : list = [1, 2, 4], n = 3 Output : list = [1, 2, 3, 4] Input : list = ['a', 'b', 'c', 'd'], n = 'e' Output : list = ['a', 'b', 'c', 'd', 'e']
Approach #1 :
This approach is the brute force method. Since the list is already sorted, we begin with a loop and check if the list element is greater than the given element. If yes, the given element need to be inserted at this position.
[1, 2, 3, 4]
Approach #2 :
Python comes with a bisect module whose purpose is to find a position in list where an element needs to be inserted to keep the list sorted. Thus we use this module to solve the given problem.
[1, 2, 3, 4]
- Python | Insert after every Nth element in a list
- Python list | insert()
- Python | Insert list in another list
- Python | Insert value after each k letters in given list of string
- Python | Split given list and insert in excel file
- Python | Insert the string at the beginning of all items in a list
- Python | Convert list of string into sorted list of integer
- List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
- Python | Indices of sorted list of list elements
- Python | Replace elements in second list with index of same element in first list
- Python | Indices list of matching element from other list
- Python | Check if list is sorted or not
- Python | Slicing list from Kth element to last element
- Python | Returning index of a sorted list
- Python | Move one list element to another list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.