Reputation: 3
Good morning, I am trying to figure out where I am going wrong in comparing two lists
def reversed_list(lst1, lst2):
for index in range(len(lst1)):
if (lst1[index] != lst2[len(lst2) - 1 - index]):
return False
else:
return True
#Uncomment the lines below when your function is done
print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))
However I get True for both values.
After scouring the Codecacademy forums, I believe the issue is that my function is simply performing one comparison and then proceeding to the return statement.
How do I go about this? I was under the impression that it would have to iterate through all of the items until it reaches the end but I suppose then it would have more than one boolean value.
im using http://pythontutor.com/visualize.html#mode=edit to step through the code line by line and im still lost. Can anyone tell me whether I need to create another object to hold the boolean values as it iterates through and then compare them at the end or if its the placement of my return function?
Thanks
Upvotes: 0
Views: 492
Reputation: 11238
when in a function call, once return
is called then all the process and code flow after the return statement don't process and the result is passed whichever is added with that return statement.
in your case here you are trying to find whether the first and last element of list1 and list2 is the same or not. if not the same then return False and if the same then return true. which is wrong as you are checking just one element and returning result according to that element only
actual approach, what you need to do check finds the element which is not equal to the element from the other list and if once such element found (mean that not reversed list) then immediately stop processing other elements and return false. if after processing all the element and no false condition arise, that means the list is reversible then return True
Below is your corrected code
# your code goes here
def reversed_list(lst1, lst2):
if len(lst1)!=len(lst2):
return False
for index in range(len(lst1)):
if (lst1[index] != lst2[len(lst2) - 1 - index]):
return False
return True
Upvotes: 0
Reputation: 9494
The problem in your code is that you return in the first iteration of your loop (whether your condition is True
or False
, you have return
in your code block).
You should change your code to something like:
def reversed_list(lst1, lst2):
for index in range(len(lst1)):
if (lst1[index] != lst2[len(lst2) - 1 - index]):
return False
return True
As a side note, much simpler solution would be:
def reversed_list(lst1, lst2):
return lst1 == lst2[::-1]
Upvotes: 1