-3

I'm trying to add a value in a ordered list but the list won't change:

def insert(V, x):

    if len(V)!=0:

        for i in range( 0 , len(V)-1):
            if (V[i]<=x)and(V[i+1]>=x):
                V=V[0:i+1]+[x]+V[i+1:len(V)]
                print("\nExpected: \n"+ repr(V))
                return

    V=V+[x]
    return

i have this:

V=[1,2,3,4,5,6,7,8,9,10]
insert(V, 6)
print("\nResult: \n"+ repr(V))enter code here

and this is the result:

Expected: 
[1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10]

Result: 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I can solve the problem setting V as the return but I want the function to work on the list.

AChampion
  • 29,683
  • 4
  • 59
  • 75
Lorenzo
  • 1
  • 1

4 Answers4

1

What you're doing can be done simply with list.insert.

As to why your function does not work, you need to update the original list using a full-slice assignment, so that the list passed to the function is updated via the current reference V:

...
V[:] = V[0:i+1] + [x] + V[i+1:len(V)]
# ^

Note that the RHS (Right Hand Side) is a new list object. Assigning to V alone rebinds the name/variable to a new list object. However, using a slice assignment ensures the original list is updated with values from the new list.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

You could just append your value to the list and sort it afterwards

l.append(value)

l.sort()

Nash
  • 105
  • 1
  • 9
0

Your function doesn't change V in place.

V=V[0:i+1]+[x]+V[i+1:len(V)]

After this line, V is no longer a reference to the list that was passed to the function, but another list. This line doesn't change the first list, but creates a new one.

You must return V and then get the result OR call a method on V, for instance list.insert().

Unatiel
  • 1,060
  • 1
  • 11
  • 17
-1

As others have pointed out, you're not modifying the original list. (Instead, you're creating a new list and then not returning it.)

Here's a solution that takes advantage of list.insert to modify the existing list:

def insert(lst, value):
    '''Insert a value into a sorted list in-place, while maintaining sort order'''

    for i, x in enumerate(lst):
        if x > value:
            lst.insert(i, value)
            return

    # fallback, in case this is the new largest
    lst.append(value)

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
insert(a, 6)
print(a)  # [1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10]

EDIT

More compact but probably harder to read:

def insert(lst, value):
    lst.insert(next((i for i, x in enumerate(lst) if x > value), len(lst)), value)
user94559
  • 59,196
  • 6
  • 103
  • 103