New to the discussion board (and Python!) so please bear with me.
Working through the practice problems for lists and can’t figure out the problem with my code.
I took an admittedly more complicated route than the suggested solution, but I still get the correct answer; however when I submit, I get the error “Function remove_at_indx did not return the expected value”
Help?
Problem
Create a function, remove_at_idx , with the following features:
Takes a list as its first argument.
Takes a positive index as its second argument.
Removes the element at the given index and decreases the index of all subsequent elements by one.
Returns a new list.
My Code
def remove_at_idx (xlist,index):
ylist = [ ]
for item in xlist:
indexcheck = xlist.index(item)
if index != indexcheck:
ylist.append(item)
return ylist
remove_at_idx(["A", "B", "C", "D", "E"], 3)
This is a very instructive mistake to make. As Bruno suggests
for i, item in enumerate(xlist):
Would have done what you wanted. I find for myself that often after spending a long time on a problem that Python has a way to do it already. In this case you can do the following
xlist.pop(index)
This is not as instructive but does demonstrate the power of Python I think.