2

I wrote a little program that inserts an element in a list. The program uses a binary search algorithm to find the spot where the new element should be allocated. I'm having trouble to change the original list content. What's wrong in my code?

def Insert(TAB,V):

    for i in range(0, len(TAB)):

        j, count = binarySearch(TAB,V)

        TAB = TAB[:j] + [V] + TAB[j:]

        return "index =",j,"comparisons =", count
5
  • 2
    TAB.insert(j,V) Commented Dec 1, 2020 at 18:10
  • Also, look into the bisect module Commented Dec 1, 2020 at 18:12
  • You want to either return TAB and have something that looks like TAB = Insert(TAB, V), or do not change the returned value but replace TAB = ... with TAB[:] = ... to change the content of the list in place. Commented Dec 1, 2020 at 18:13
  • I want to replace the original list with the new list that includes the new element. Commented Dec 1, 2020 at 18:14
  • @inspectorG4dget I can't use bisect module. It's an assignment from uni. Commented Dec 1, 2020 at 18:14

1 Answer 1

2
    TAB = TAB[:j] + [V] + TAB[j:]

This builds a new list and assigns it to the local variable TAB. IF you expect to change the list in the calling program, then you have to operate directly on that list, not assign to its local avatar.

TAB.insert(j, V)

should do the job.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.