Skip to content
Advertisement

How to change list content after applying a function in Python

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

Advertisement

Answer

    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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement