By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,715 Members | 768 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,715 IT Pros & Developers. It's quick & easy.

debugging a simple code.

P: 31
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...
Expand|Select|Wrap|Line Numbers
  1. def reverse(L):
  2.     """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.""" 
  3.     M=list()
  4.     for i in L:
  5.         M.append(L[i])
  6.         M.reverse()
  7.     return M
Feb 9 '09 #1
Share this Question
Share on Google+
2 Replies


boxfish
Expert 100+
P: 469
These lines are the problem:
Expand|Select|Wrap|Line Numbers
  1. for i in L:
  2.     M.append(L[i])
i contains items from the list, not list indices. The code should be
Expand|Select|Wrap|Line Numbers
  1. for i in L:
  2.     M.append(i)
However, a more compact way to copy a list is with a slice:
Expand|Select|Wrap|Line Numbers
  1. M = L[:]
I hope this is helpful.
Feb 9 '09 #2

bvdet
Expert Mod 2.5K+
P: 2,851
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.
Expand|Select|Wrap|Line Numbers
  1. >>> aList = [0,1,2,3,4,5,6,7,8,9]
  2. >>> anotherList = aList[::-1]
  3. >>> aList
  4. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  5. >>> anotherList
  6. [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
  7. >>> anotherList2 = [aList[i] for i in range(len(aList)-1, -1, -1)]
  8. >>> anotherList2
  9. [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
  10. >>> 
Feb 9 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.