A question about challenge no. 5 (Titled “Reversed List”) in “Python Code Challenges: Loops (Advanced)” in the Computer Science Stream.

def reversed_list(lst1, lst2):
for index in range(len(lst1)):
if lst1[index] != lst2[-1-index]:
return False
return True

This answer is wrong, however I do not understand how? As in the context of the exercise, this code should be equivalent to the solution provided by Codecademy, which is:

def reversed_list(lst1, lst2):
for index in range(len(lst1)):
if lst1[index] != lst2[len(lst2) - 1 - index]:
return False
return True

If someone can look up this question on Codecademy and explain to me what I did wrong, I would greatly appreciate it!

It’s a little hard to see at the moment as the forums have stripped your code of the standard formatting but there’s only one difference in the code, which is that the indexing is different.

Maybe you could try printing out those values to see how the index differs between your solution and the cc option.

In the future could you please format the code as per How do I format code in my posts?; Python without indentation is scary. Linking the lesson, project or article page might also be useful. Cheers.

2 Likes

Hi there,

I will rewrite the code below with indentation:

``````def reversed_list(lst1, lst2):
for i in range(len(lst1)):
if lst1[i] != lst2[-1-i]:
return False
else:
return True
``````

CC’s solution:

``````def reversed_list(lst1, lst2):
for index in range(len(lst1)):
if lst1[index] != lst2[len(lst2) - 1 - index]:
return False
return True
``````

This question asks you to compare the element in the first list(lst1) at the current index against the element at the second list’s(lst2) last index (the lists are the same length) to see whether the second list is the reverse of the first list.
I don’t understand as to how my answer is not equivalent to CC’s solution for the part where lst1[index] != lst2[-1-index] in my code should be equivalent to ** if lst1[index] != lst2[len(lst2) - 1 - index]:** in CC’s code. The only difference is that I am using negative indices to access the second list’s elements from back to front.

The else statement inside the for loop
so when after tests the first character,
the function will return `False` if the first character of `lst1` is not the same as the last character of `lst2`
and if those characters are the same, the function returns `true`,
but
the loop never gets to next iteration (and testing the next character),
because the function (and therefore executing the loop) ends once it reaches return

you don’t actually want it to do only one iteration …
if the first letter matches, you want to check if the next letter matches, and so on.

so you can’t have an else statement that includes a return
inside of the for loop

3 Likes

Hi there,