debugging a simple code.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • v13tn1g
    New Member
    • Feb 2009
    • 31

    debugging a simple code.

    I have a function that won't work is it possible for someone to debug it for me?...i've been trying to play with everything...
    Code:
    def reverse(L):
        """Given a list, return a new list that is the same as the original list except that its members are in reverse order, without changing the original.""" 
        M=list()
        for i in L:
            M.append(L[i])
            M.reverse()
        return M
    Last edited by pbmods; Feb 10 '09, 12:13 AM. Reason: Added CODE tags.
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    These lines are the problem:
    Code:
    for i in L:
        M.append(L[i])
    i contains items from the list, not list indices. The code should be
    Code:
    for i in L:
        M.append(i)
    However, a more compact way to copy a list is with a slice:
    Code:
    M = L[:]
    I hope this is helpful.

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      To give you some alternatives, you can create a reversed list using the slice operator and the range function in a list comprehension. You could also use a for loop in combination with range() instead of the comprehension.
      Code:
      >>> aList = [0,1,2,3,4,5,6,7,8,9]
      >>> anotherList = aList[::-1]
      >>> aList
      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
      >>> anotherList
      [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
      >>> anotherList2 = [aList[i] for i in range(len(aList)-1, -1, -1)]
      >>> anotherList2
      [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
      >>>

      Comment

      Working...