Python Forum
Function to return modified list
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)
Reply
#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)
Reply
#3
That worked like a charm, thanks so much.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do I calculate a ratio from 2 numbers and return an equivalent list of about 1000 Pleiades 8 15,446 Jan-05-2024, 08:30 PM
Last Post: sgrey
  nested function return MHGhonaim 2 562 Oct-02-2023, 09:21 AM
Last Post: deanhystad
  return next item each time a function is executed User3000 19 2,176 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  PDF properties doesn't show created or modified date Pedroski55 4 1,007 Jun-19-2023, 08:09 AM
Last Post: Pedroski55
  function return boolean based on GPIO pin reading caslor 2 1,131 Feb-04-2023, 12:30 PM
Last Post: caslor
  Need to parse a list of boolean columns inside a list and return true values Python84 4 2,037 Jan-09-2022, 02:39 AM
Last Post: Python84
  return vs. print in nested function example Mark17 4 1,674 Jan-04-2022, 06:02 PM
Last Post: jefsummers
  append a string to a modified line Mr_Blue 10 3,731 Sep-16-2021, 07:24 PM
Last Post: Mr_Blue
  How to invoke a function with return statement in list comprehension? maiya 4 2,753 Jul-17-2021, 04:30 PM
Last Post: maiya
  Function - Return multiple values tester_V 10 4,321 Jun-02-2021, 05:34 AM
Last Post: tester_V

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020