Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Function to return modified list
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.

# 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)

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

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.

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  I created a function that generate a list but the list is empty in a new .py file mrhopeedu 2 105 Oct-12-2019, 08:02 PM
Last Post: mrhopeedu
  Custom Function to Return Database Values rm78 0 98 Sep-05-2019, 01:01 PM
Last Post: rm78
  [SOLVED ]ValueError: View function did not return a response Hadad 0 249 Jul-24-2019, 04:01 PM
Last Post: Hadad
  Search a List of Dictionaries by Key-Value Pair; Return Dictionary/ies Containing KV dn237 19 702 May-29-2019, 02:27 AM
Last Post: heiner55
  Return all Path value from function Palerm0_24 2 305 Mar-18-2019, 03:09 PM
Last Post: ichabod801
  List creation and return in Function leoahum 3 326 Mar-04-2019, 04:45 PM
Last Post: leoahum
  Function and return value Roh_80 1 363 Jan-24-2019, 03:15 PM
Last Post: buran
  modified file text getting cut off droidus 3 445 Jan-22-2019, 01:55 PM
Last Post: droidus
  how to use the return function NLittle17 5 597 Jan-08-2019, 12:01 AM
Last Post: ichabod801
  Use variable from one function in another without return P13N 3 419 Dec-25-2018, 05:57 PM
Last Post: stullis

Forum Jump:

Users browsing this thread: 1 Guest(s)