 The code I typed returns the correct answers (true, false), but I get an error that says “list index out of range”?

Why is that?

``````#Write your function here

def reversed_list(lst1, lst2):

for index in range(len(lst1)):
if lst1 != lst2:
return False
break
elif lst1 != lst2:
return False
break
elif lst1 != lst2:
return False
break
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]))
``````

the link below is a screenshot of how the error is coming up because it is not in the terminal.

https://gyazo.com/8ea2565e41450f3f5f9644f54dbb630a

Hello, @script8409387171!

The error message that you’re getting says that list index is out of range.

Let me cite an example to help you understand what this error message means. Refer below:

``````list_a = [1, 2 , 3]
# this list has only 3 elements but list index starts from 0 so these elements can be accessed using the indices 0, 1 and 2.
print(list_a) # This statement will print value 3
print(list_a) # This statement will throw an error
``````

However, if you look at the question of the challenge, you’re trying to attempt the solution in a different way.
The challenge statement says to write a function which accepts two lists of same sizes and should return True if list1 is the same as list2 reversed.

Your solution does involve a loop but is it really using the loop? You have just declared a loop which iterates for the length of the list but you’re not actually doing anything with the loop.
You’ve actually hard coded the values of the indices in the loop which is visible in the following code:

``````if lst1 != lst2:
return False
break
elif lst1 != lst2:
return False
break
elif lst1 != lst2:
return False
break
else:
return True
``````

Can you come up with a way to compare the elements using the index that you’re using in the loop?
`for index in range(len(lst1)):`

You can access the elements of list using:
`lst1[index]`

and if you want to access the elements from the end of the array, you can use something like:
`lst2[len(lst2) - 1 - index]`

And then compare these elements using the loop instead of hard coding the values.

Try implementing a solution in this way and the challenge will be solved! Happy Coding!

1 Like