Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Function to return modified list
#1
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)
Quote
#2
(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)
Quote
#3
That worked like a charm, thanks so much.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  reading txt file putting in list function Expel 7 97 Jul-17-2019, 03:18 PM
Last Post: Expel
  Why does this return False? gunitinug 1 62 Jul-13-2019, 07:11 AM
Last Post: perfringo
  Need help with 'return' in python Leo12143 2 205 Jul-10-2019, 02:35 AM
Last Post: SheeppOSU
  generator function that yield from a list buran 9 427 Jun-04-2019, 10:26 PM
Last Post: snippsat
  Search a List of Dictionaries by Key-Value Pair; Return Dictionary/ies Containing KV dn237 19 523 May-29-2019, 02:27 AM
Last Post: heiner55
  AssertionError: View function mapping is overwriting an existing endpoint function Zhavi221 7 675 Apr-17-2019, 01:07 PM
Last Post: Zhavi221
  Return all Path value from function Palerm0_24 2 199 Mar-18-2019, 03:09 PM
Last Post: ichabod801
  How to continue after "return" Helmi 4 350 Mar-17-2019, 09:26 PM
Last Post: Helmi
  List creation and return in Function leoahum 3 200 Mar-04-2019, 04:45 PM
Last Post: leoahum
  Function and return value Roh_80 1 257 Jan-24-2019, 03:15 PM
Last Post: buran

Forum Jump:


Users browsing this thread: 1 Guest(s)