#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    22
    Rep Power
    0

    Ebook question help needed


    im having trouble with this exercise.

    Exercise 10.2 Write a function called chop that takes a list and modifies it, removing the first and
    last elements, and returns None.

    Then write a function called middle that takes a list and returns a new list that contains all but the
    first and last elements.

    I think I can do the second part, I came up with-

    Code:
    t=[1,2,3,4]
    
    def middle(t):
        return t[1:len(t)-1]
    
    print(middle(t))
    The first part has me stumped tho, I came up with this-

    Code:
    t=[1,2,3,4]
    
    
    def chop(t):
        del t[0:len(t)-1]
        
    
    print(chop(t))
    It returns None but it doesn't look right and im not sure that this is what the question is asking for. Some advice would be appreciated.
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,995
    Rep Power
    481

    Useful trick: Index from the right end


    [code>>> t=[1,2,3,4]
    >>> def chop(t):
    del t[0], t[-1]
    # or
    # del t[0]
    # del t[-1]


    >>> chop(t)
    >>> t
    [2, 3]
    >>> def middle(t):
    return t[1:-1]

    >>> middle(t)
    []
    >>> [/code]

    Comments on this post

    • Nykinum agrees
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo