Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert an item into sorted list in Python

I'm creating a class where one of the methods inserts a new item into the sorted list. The item is inserted in the corrected (sorted) position in the sorted list. I'm not allowed to use any built-in list functions or methods other than [], [:], +, and len though. This is the part that's really confusing to me.

What would be the best way in going about this?

like image 555
Will S Avatar asked Nov 06 '11 01:11

Will S


People also ask

How do you add an item to a list at a specific position?

You can add an item to a list with the append() method. A new item is added at the end. If you want to add to other positions, such as the beginning, use the insert() method described later. A list is also added as one item, not combined.

What is the procedure to insert into a sorted array?

Insert Operation: In a sorted array, a search operation is performed for the possible position of the given element by using Binary search, and then an insert operation is performed followed by shifting the elements.


1 Answers

Use the insort function of the bisect module:

import bisect  a = [1, 2, 4, 5]  bisect.insort(a, 3)  print(a) 

Output

[1, 2, 3, 4, 5]  
like image 163
stanga Avatar answered Sep 20 '22 05:09

stanga