Link to home
Start Free TrialLog in
Avatar of ittechlab
ittechlabFlag for Canada

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
ASKER CERTIFIED SOLUTION
Avatar of Abhishek Kumar
Abhishek Kumar

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gelonida
One of Python's strengths is that it has many 'batteries included'.

Knowing, that your list is sorted,  you can directly use Python's bisect module. ( https://docs.python.org/2/library/bisect.html )

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.
import bisect
l1 = [10,20,30,40,50]
for n in [ 0, 35, 55]:
    l1.insert(bisect.bisect_left(l1, n), n)
    print(l1)

Open in new window