ittechlab
asked on
phython
i want to insert 35 between 30 and 40. need to know what is the better way to do this as my code is not working properly
l1 = [10,20,30,40,50]
n=35
for e in l1:
if e < n:
print e
print l1.index(e)
l1.insert(l1.index(e),n)
print l1
l1 = [10,20,30,40,50]
n=35
for e in l1:
if e < n:
print e
print l1.index(e)
l1.insert(l1.index(e),n)
print l1
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Knowing, that your list is sorted, you can directly use Python's bisect module. ( https://docs.python.org/2/
For huge lists it will locate the right place much faster than your approach.
bisect is of order log(n) whereas your approach is of order n.
I often wrote small code snippets just to find out later, that Python had already a solution included.
On the other hand: I learnt a lot about coding when trying to code my implementations myself
Her a small example using bisect, showing it handles boundary cases well.
Open in new window