-1

assume L is a list f and g are defined function

def function(L,f,g):
    newL = list()
    for i in L:
        if g(f(i)) == True:
            newL.append(i)

    L[:] = newL

    if len(L) == 0:
        return -1
    else:
        return max(L)

def f(i):
    return i + 2
def g(i):
    return i > 5

L = [0, -10, 5, 6, -4]
print(function(L, f,g))
print(L)

Using L = newL[:] will cause print(L) to print L = [0, -10, 5, 6, -4]. But if inside function I use L[:] = newL, print(L), this will make print(L) give me the result of newL [5,6] - which is what I want To me, both L = newL[:] and L[:] = newL will give me the same result. But in reality, it did not. So, can anyone provide me an explanation of this?

Derek Gu
  • 21
  • 3
  • 1
    I do not understand the question? What part do you not understand? `L[:] = newL` makes a shallow copy of `newL` and it alters the list `L` such that `L` is now that copy. – Willem Van Onsem Sep 03 '17 at 19:30
  • If I use L = newL[:] print(L) will give me [0,-10,5,6,-4] but if I use L[:] = newL print(L) will give me [5,6] which is what I want. My question is that to me both of them are the same, but I. Reality they did not produce same result. Why is that? – Derek Gu Sep 03 '17 at 19:57
  • Possible duplicate of [How assignment works with python list slice](https://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice) – Tadhg McDonald-Jensen Sep 03 '17 at 21:04
  • Possible duplicate of [What is the difference between slice assignment that slices the whole list and direct assignment?](https://stackoverflow.com/questions/10155951/what-is-the-difference-between-slice-assignment-that-slices-the-whole-list-and-d) – Tadhg McDonald-Jensen Sep 03 '17 at 21:22

1 Answers1

0

It's a scope issue. Lists created in the global space are changeable within a function because with this line:

L[:] = newL

you are operating on a reference to the global list, not a local copy of it. Therefore, the last line of your program prints the changed list. Whereas this version:

L = newL[:]

...is operating on a local copy of the list, so the last line of your program prints the global as it was before the function call.

Play around with this modified version:

def function(L,f,g):
    newL = list()
    for i in L:
        if g(f(i)) == True:
            newL.append(i)

    L = newL[:]
    #L[:] = newL

    print('inner L = ', L)
    if len(L) == 0:
        return -1
    else:
        return max(L)

def f(i):
    return i + 2
def g(i):
    return i > 5

L = [0, -10, 5, 6, -4]
print(function(L, f,g))
print('outer L =', L)
RustyB
  • 147
  • 1
  • 11