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 | Insert Nth element to Kth element in other list
- Python list | insert()
- Python | Insert list in another list
- Python | Insert value after each k letters in given list of string
- Python | Insert the string at the beginning of all items in a list
- Python | Split given list and insert in excel file
- 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 | Subtract two list elements if element in first list is greater
- Python | Replace elements in second list with index of same element in first list
- Python | Check if list is sorted or not
- Python | Indices list of matching element from other list
- Python | Slicing list from Kth element to last element