Codecademy Forums

How can I iterate over a list backward?

They are in situ operations, as in the happen in place.

Just as list.sort() has its counterpart, sorted(my_list), list.reverse() has its counterpart, reversed(my_list). the latter in each case return a new list, where the former are in place.

2 Likes

This one worked for me:

def reversed_list(lst1, lst2):
  if lst1 == lst2[::-1]:
    return True
  else:
    return False

Can someone tell me why this code(1) works:

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

And this code(2) doesn’t:

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

I don’t understand why code(1) doesn’t always return true regardless of lst1 and lst2 because I thought that the lower return value after the for loop would override the boolean of the function due to its indent and being the last call.

Any help with this would be much appreciated.

Many thanks.

Please preserve the indents by making use of the </> icon in the menu bar that appears atop the text box when you type in it.

So long as we can assume the given form,

for ...:
    if ...:
        return False
return True

then the logic is sound.

When there is a return True in the else clause within the loop then the function terminates at that point, without completing the loop.

@mtf Thank you for your very clear explanation. Much obliged :slight_smile:

1 Like

Hi guys,

I can’t figure out why the returns at the bottom of the code are indented like that. Any explanation so I can learn to use this format? See my posted picture/screenshot!

wow, this is super helpful! Learned a new way of writing code!

Why both continue and pass can complete this exercise.

#Write your function here
def reversed_list(lst1, lst2):
  for i in range(1,(len(lst1)+1)):
    if lst1[i-1] == lst2[-i]:
      continue
    else:
      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]))


Doing nothing this iteration and moving on to next iteration is the same thing.
You only need to do something for one of the cases. You can remove the other.

if different:
    return False

Also, that code makes me nervous.
That math is really error prone, and it can be avoided.

Consider:

def is_reverse_of(a, b):
    return all(aa == bb for (aa, bb) in zip(a, reversed(b)))

or with fewer crazy things, I guess:

def is_reverse_of(a, b):
    a_is = range(len(a))
    b_is = range(len(b))[::-1]

    for ia, ib in zip(a_is, b_is):
        ...

I have not learned this form of slice

If you know it’s a slice then you arguably know enough. The arguments are like that of range, the step there is -1 and start/stop get default values when they are left out. So it just says: step backwards.

The main point though, is that complicated math with indexes are something to be avoided if possible. We can abstract that away, remove the possibility of getting it wrong.

I didn t understand why
lst2[len(lst2) - 1 - index] would reflect the reverse of the indexes, in base of which logic reason?
thank you for your help

1 Like

len(lst2) - 1 will give you the right most value, by increasing index variable you will go from right to left over the list

Still don’t get this…

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

# I struggle to understand what it means:
lst1[index]  - # starts at 0 ?
lst2[len(lst2) - 1 - index #I read as starts at 2 - 1 - index 

Write down some word on a piece of paper in big letters.
Point your left hand at the first letter
Point your right hand at the last letter
Repeat:
Compare what you’re pointing at
Move both hands towards the other end of the word

Alternatively, READ the code. Evaluate in your head what happens and follow along, observing.

1 Like

tnx; did that and run it trough the vscode debugger.

it’s something like this:

3 - 1 - 0 = position : 2 = <number 1>
3 - 1 - 1 = position : 1 = <number 2>
3 - 1 - 2 = position : 0 = <number 3>

makes sense now…

still don’t know why I can’t use reverse()

Thanks a lot, It’s much more clear now! :grinning: :sweat_smile:

I remember it was covered but failed to remember…

#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 am really confused as well. I don’t know why I have to unindent “return True” instead of writing:

else:
return True