More practice with loops

Hello again,

I am working on the Reversed List challenge here.

I wrote the following:

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

#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]))

I got False for both.

The correct code is:

#Write your function here
def reversed_list(lst1, lst2):
  for index in range(len(lst1)):
    if lst1[index] != lst2[len(lst2) - 1 - index]:
      return False
  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]))

I don’t understand why my code would return False.
Also I seem to need more practice with loops, is there any recommended places for me to get more questions to help me solidify this concept?

Thanks!

1 Like

Ok,

I changed
if index == lst2[len(lst2) - 1 - index]:
to

if lst1[index] == lst2[len(lst2) - 1 - index]:

and it worked!

Could someone please explain what I changed.

Secondly could I please get another explanation on what exactly range(len(lst1)) means because I think that’s where I am messing up.

1 Like

Execute them manually. In your head or on paper.
And/or add prints to write out what’s being done.

The code already answers your question. So you should be reading it.

If something prevents you from reading it, then that something should be identified, and learned, and then you can keep going. (Can’t meaningfully write code that you don’t understand, so whatever you write you also have to learn)

2 Likes

I was trying a few things out and wrote the following:

#list
lst1 = [1,2,3,4,5,6,7]
lst2 = [1,2,3,4,5,6,100]
print(len(lst1))
>>>7 #Which I knew is what I should get
print(range(len(lst1)))
>>> range(0,7)  
print(range(len(lst2)))
>>>range(0,7)

Just to clarify, for myself, the code range(len(list))) will give the out put of how many index there are in the list correct?

No, range doesn’t return a number. It creates a list, or in python3 a range object which behaves a lot like a list.
The amount of indices can be obtained with the len function