Sorting a list dynamically in Python

The Bisect module in python sorts the dynamic list,whenever we insert the value rather than sorting after inserting all the values into list.

Source code :

import bisect
import random
random.seed(1)
left = []

for i in range(1, 6):
    right = random.randint(1, 50)
    pos = bisect.bisect(left, right)
    bisect.insort(left, right)
    print '%2d %2d' % (right, pos), left


Output :

 7  0 [7]
43  1 [7, 43]
39  1 [7, 39, 43]
13  1 [7, 13, 39, 43]
25  2 [7, 13, 25, 39, 43]

Notes :

Random module generates 5 (range 1 to 6) random values between 1 to 50.The first column is the random value which has been inserted and second column represents the position in the list.


Output :


                

Comments :