Python Forum

Full Version: Function to return modified list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I am about a month into python and what I am trying to do is write a function that takes a list passed to it, make a copy of that list so as to not modify the original. Then simply strip the first and last items in the list and return the modified list. When I do this I can see via a print statement in the function, that the list copy has been modified and the original is intact but I seem to get back the original list. I know its because the print function after I call the function is using the original list variable but I am a little confused on how to reference the returned list. I can't use the new list variable I defined in the function since I receive a traceback that the name is not defined. These modifications have to be done in a function. I have the code below.
Thanks a lot for any help.
Paul

# This funnction takes a list, modifies/removes first and last items from the list
def KeepOnlyMiddle(t):
    print('The list is: ', t)
    tnew = t[:]
    del tnew[0]
    print('tnew is ' , tnew)
    t3 = tnew.pop()
    print('tnew is now' , tnew)
    return(tnew)

MyList = [1,2,3,4,5,6]
KeepOnlyMiddle(MyList)
print('List called MyList is: ', MyList)
(Feb-06-2019, 10:40 PM)Pjones006 Wrote: [ -> ]MyList = [1,2,3,4,5,6]
KeepOnlyMiddle(MyList)


If you want to use the returned value, assign it to a variable.

MyList = [1, 2, 3, 4, 5, 6]
MyList = KeepOnlyMiddle(MyList)
That worked like a charm, thanks so much.