Did you double check the placement of `return`?

Thank you! Yes i am new in forum and didn’t find how to change name))

Yes it won’t work with that input “print(reversed_list(, [1, 2]))”, but in this task it says that “two lists of the same size” - it’s work only if so

1 Like

You are correct regarding the instructions. I just like to push the boundaries :slightly_smiling_face:

just change the test expression and it will work :

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

print(reversed_list([1, 2, 3], [3, 2, 1]))
#True
print(reversed_list([1, 5, 3], [3, 2, 1]))
#False

I used this code. It looks short and working.

def reversed_list(lst1,lst2):
    lst2.reverse()
    if lst1==lst2:
        return True
    else:
        return False

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

Here’s my solution after MANY attempts:

#Write your function here
def reversed_list(lst1, lst2):
  # Validate
  if len(lst1) == 0 or len(lst2) == 0:
    return False
  if not len(lst1) == len(lst2):
    return False
  
  # Evaluate
  for index in range(len(lst1)):   
    if not lst1[index] == lst2[len(lst2) - 1 - index]:
      return False
  return True
  
#Test
print(reversed_list([1, 2, 3], [3, 2, 1])) # True
print(reversed_list([1, 5, 3], [3, 2, 1])) # False
print(reversed_list([], [1, 2])) # False

Hey all,

I have a small logic question on this one. I’ve thought it over, looked over my notes, and I’m still stumped. And I admit I had to run to the hint real quick on this one, for what that’s worth. That math gave me pause before I parsed it out in my head.

Input:

print(reversed_list([1, 2, 3], [3, 2, 1]))
print(reversed_list([1, 5, 3], [3, 2, 1]))

So, the correct answer is:

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

This is totally cool. I understand the syntax (rare for me as a beginner) and the logic perfectly fine. What I do not understand is why my attempt returned True on the second list instead of False. My answer was:

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

The main difference that I can see is that the correct answer checked for != to return False, whereas I checked for == to return True. As an experiment, I kept everything in my answer the same but changed my == to !=, my True to False, and my False to True, and it worked correctly.

My question is: why does my comparison, which should compare 5 and 2 and find them not equal, not kick in my else clause? I moved the indentation around to see if it worked in or out of the loop and there was no change. Can anyone explain the logic to me?

Thank you so much.

if do the following function call to your function:

print(reversed_list([1, 5, 3], [3, 2, 1]))

i get True, while it should be False.

Do you want me to explain this to you, or do you want some more time to fiddle with it?

You have for-else in your code. What does that do?
If you don’t know, then you have no reason to expect any particular behaviour from your code.
What you can do however, is to leverage things that you do know.

Don’t move things around arbitrarily. Ask yourself what you meant, and write that. No guessing. It’s up to you to make sure all the actions are aligned to create a connection between the starting state and the ending state you are looking for.

I also wonder how many times you think your function executes a return statement. And, if it’s more than one time, then which of them is the result of the function? That doesn’t add up, does it? What does return do, what is its effect? You’d have to know that in order to leverage it to get the effect you want.

Also consider adding lots of prints in your code to write out in English as if the program was explaining what it was doing to you. If you don’t know what it does, looking is a good idea.

And if some particular language feature doesn’t behave like you expect then write a simpler program that uses only that feature so that you can test it better. (and/or research it)

1 Like

@stetim94: Yes, I would like a breakdown. I can’t move on until I got all of the logic and syntax down. The frustrating part is that the logic has always been the easy bit for me, but here it just totally escapes notice.

@ionatan: I understand your point, but the movement wasn’t arbitrary. In one of the prior exercises, moving the return command into or out of the loop gave me different answers, and once I saw the behavior, I was able to use that change to find out exactly why it did what it did. I know the inputs can only be these numbers, so if it added this one again here, but not there, it tells me something about how the loop functions.

I gather you see what I did wrong and are trying to lead me to the light on my own, so to speak. So, though I did ask stetim94 to lay it all out for me, I’ll at least explain what I’m seeing so you can point at where I am wrong.

In my mind, the “for” loop should run through everything in the list. As that is the case, it should run everything in the lists before deciding on a True verdict. The very instant it finds that 5 is not 2, it should stop, and check the Else clause.

What I am suspecting from your words is that the return function is returning True for every iteration in the list until it hits one that does not fulfill the requirements. Since the requirement was filled (once), it returns True, and since that was the case, no need to check the Else clause, and have a nice day.

If this is what happened, then my understanding of a “for” loop running through the list needs to be adjusted, as in my mind it should run the whole thing every time before deciding on what to return.

Or perhaps I’m totally off base. In any case, this is why I asked for an explanation of the logic. Something I think I know is wrong. It needs to be replaced and practiced. I do like your advice about adding print functions intermittently in the code to make sure the code is transparent, if you will. I think I shall do so from now on.

have you tested this statement is actually true? Very easy to do with a print statement:

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

return is literally what it says, handing something back

imaging making a test, where each question represents an iteration of a loop. You can perfectly hand back the test to the teacher after only filling in one question.

1 Like

You had two possible locations and you tried both. How did you choose between them before running it? Arbitrarily, right? That’s a bit like changing for to if to def in hopes of that one might “click”. Which one did you mean, use that.

Should this line be inside a loop, or outside it? It’s not something you should be trying different indentations for, it’s something to ask yourself, and then place it there.

You have to finish before exiting your function, yes. But have you finished by the time you encounter a return statement?

Also, you’re saying “why doesn’t this work” - that must mean that you think it should work. Do you have an understanding of what each thing does in your code, can you execute it in your head? If not, then I don’t think you should be asking the question because then you can’t argue that it would work. What you can be doing though is to identify what you don’t know, research it, keep going, repeat until understood, and then you should be able to answer yourself what it does by having learned what the individual parts do. Identifying what you don’t know can be either through integrity checking your own knowledge (“do I know this?”) while you read your own code, or if that fails (think you understand everything) then you’ve proved that some part of your understanding is wrong at which part you’ll need to start picking things apart to identify which. That can be done by printing things out or by literally picking it apart, making smaller programs that still don’t behave like you expect. And if that still fails (should be rare, because things don’t interact in crazy things) then explaining your understanding of a minimal piece of code that reproduces the mystery would let others poke holes at your reasoning.

I’m probably overusing the word “should” here. It’s not in the moral sense, it’s about possible paths of reasoning.

2 Likes

A small disclaimer: I am not trying to be difficult. Honest.

@stetim94: Using your print line, your point is made. My version checked index 0 and only index 0, and returned True both times. The correct version ran 0-2, returned True, and then 0, 1, and False.

I went back and looked at the lesson on loops (specifically “for” loops) and I think the part I’m struggling with is when then lesson says

A for loop lets us perform an action on each item in a list. Using each element of a list is known as iterating .

To me, that reads as a “for” loop will run the entirety of what’s available. Each item means every item, which is why I can’t wrap my head around why my “for” loop doesn’t seem to want to do that, but doing it the opposite way does. I typed “for”, which means run each item. It only runs one.

Either I don’t understand “for” loops, or I don’t understand Return, or I don’t understand True and False, or some lovely little mix of all three.

I think my frustration is that I’ve made it this far. I went through each lesson, not skipping anything. I read and read again. I can’t find my error. I literally cannot find it.

imaging making a test, where each question represents an iteration of a loop. You can perfectly hand back the test to the teacher after only filling in one question

My understanding of this, if I am understanding the metaphor correctly, is that the way I did it allowed it to find something True and stop, whereas the other way was “looking” for False, and so it had to keep going in order to find False. Is this accurate?

@ionatan:

What you can be doing though is to identify what you don’t know, research it, keep going, repeat until understood, and then you should be able to answer yourself what it does by having learned what the individual parts do.

And that’s the problem. I thought I did know. I don’t, and my struggle with this one problem makes it very much clear. I can’t identify what I don’t know, because from everything I’ve read, and from being able to make it this far, I’ve convinced myself I do know. As I said above, the lesson said the “for” loops run each item. My “for” loop only ran one item. Right here, I’m lost. Which is it? Does it run every item? Does it only do the bare minimum to fulfill some condition?

I would love to go back and devote more time to whatever concept is making this opaque to me. Which concept? “For” loops? If clauses? Else clauses? Return? True? False? What? What did I do wrong? I suspect you will say “you should go back through each one and make sure you understand it.” I do. I do so every night, because I am trying to move on, and the fact that I can go back and pass the prior lessons, and the prior challenges, suggests to me that my understanding was fine. But it isn’t, and if it isn’t fine after taking all of the prior lessons again, the prior lessons aren’t going to fix it. I’m just trying to pinpoint what, specifically, I missed, so I can go back, see me doing it unconsciously in all of the prior examples, “rewrite” the erroneous concept in my head, and proceed.

Also, you’re saying “why doesn’t this work” - that must mean that you think it should work. Do you have an understanding of what each thing does in your code, can you execute it in your head?

I thought it would work, and I still think it should. That’s why I’m whining about this as much as I am.

Which one did you mean, use that .

I meant the one which ran every item in a list, which is “for”. It didn’t run every item. Why?

I’m presented with a row of numbered tokens and instructed to present them in reverse order. I must use my hands because they are tokens I have to manipulate.

Intuitively we start by switching the outermost two, then the next outermost, and so on until we reach the middle. Now convey this process to a program following the same procedure. From @ionatan’s standpoint of view, this would be a veritable garden.

Forgive my jumping in here, but I sense you are becoming quite frustrated with trying to understand what is happening in the interaction of your for loop and the return statement. Let me try to explain with a much simpler example. Examine the following code and its output:

one_to_10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def count_to_ten (numbers):
    for number in numbers: #iterates the entire numbers list unless interrupted
        print(number) #prints each number in turn
    return 'I have finished counting to ten.' #returns the string literal to the caller after the for loop has finished executing

print (count_to_ten(one_to_10)) #calls the count_to_ten function and prints the value returned

Output:

1
2
3
4
5
6
7
8
9
10
I have finished counting to ten.

That code did exactly what you would expect a for loop to do. It iterated over the entire list, but what if we interrupt the execution of the for loop with a return statement? It’s important to note, and always remember what the return statement does. return sends the control back to the line of code that called the function. return ALWAYS sends control back to the caller. See the following example:

one_to_10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def count_to_ten (numbers):
    for number in numbers: #iterates the entire numbers list unless interrupted
        print(number) #prints each number in turn
        if number == 5:
            return 'I got tired, and quit counting after 5. Sorry.' # if/when this line is executed control goes back to the caller, and the for loop cannot finish iterating over the list
    return 'I have finished counting to ten.' #this line will not be reached if the number 5 exists in the list

print (count_to_ten(one_to_10)) #calls the count_to_ten function and prints the value returned

Output:

1
2
3
4
5
I got tired, and quit counting after 5. Sorry.

See what happend? The for loop was interrupted by the nested return statement. Any time we want to fully iterate over a collection of data, we need to make sure there is nothing inside the code which would prevent the iteration from running to completion. Hopefully this has helped shed some light on your dilemma. Happy coding!

If you have a understanding, great, write code based on that. If you prove yourself wrong, even better. When that happens, what part of your understanding didn’t hold? Try things isolated from each other so that you can tell which is the cause.

For looking things up, google them.

I asked how many times you think your function executes a return statement. You can only execute a return statement once, but you have it in a loop (and a condition that can be satisfied more than once). Either you think it’ll only happen once and you’ve got the rest of the logic wrong, or you think you can return multiple times in which case I have no idea what you think return does.

Do you have an understanding (right or wrong) of what return does? Maybe you’d even find that you can’t explain it, that there’s actually a hole in your understanding that you are blind to. Or maybe you think it does something else. Writing code based on your understanding will test that understanding, and that makes mistakes really important, they tell you what to learn. Don’t make textual modifications without knowing why you’re making them (like changing indentation), instead think about what you meant that it was supposed to be.

If you end up writing something that you’ve never seen before, like for-else, then something went terribly wrong in the process leading to that. You can’t argue that for-else should work if you’ve never seen it. You can’t even think that you understand it, there is definitely a hole in that understanding. A guess did happen.

If you read your code and try to execute it in your head, what do you do when you encounter for-else? You have to stop executing, you don’t know it. What you might be doing here is to instead execute your idea of what should be happening, so you’re glossing over anything you don’t know. No, no, no. It’s the code that you should be executing.

Humans tend to fill in blanks and auto-correct things. That’s not helpful when reading code because that isn’t how code gets executed. If something is slightly wrong, if something is slightly unspecified, then that has to get fixed.

1 Like

Let’s real quick dismiss the idea of thinking that this should work.
it has for-else in it. What does for-else do? Don’t know. There’s something in it that we don’t know what it does. Does it work? Yeah. Wait, no, I don’t know what it does.
Great.

And then, how was it obtained?
Arbitrarily indenting something.
Okay. So that led to something senseless, let’s just not do that.

Writing code is to describe a process.
To describe something, use words you know.

Where should return False be?
I agree that it should be somewhere, because that’s a possible result of the function.
Should it
a) be inside the loop
b) be after the loop
Those are some really different things. Refer to your original idea, is this something repeated? Okay, then put it there.

So, maybe you then have it in the loop.

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

Cool, all the operations here are something I understand.
For each location in lst1, make some comparison, and return either True, or otherwise False.

So each iteration, something is returned.

Let’s say lst1 is 5 long. That would mean there are 5 results.
Which result is … the result?
To me this seems like a back-to-the-drawing-board kind of situation. This wasn’t thought through. There needs to be ONE result. What can the function do to obtain one single result? Do that, and return it.

If at this point it seems impossible to know what to change, then, no, it’s not. You already know this. You, by virtue of being human, are able to manually carry out this task. So what do you do? Study yourself, what is the general algorithm that you use? Maybe you’d want to write this down in English, as instructions. Code is instructions. Then start translating the English text into code. You may need to break down the English version into smaller parts that you know how to write code for, but your program will be doing exactly the same thing and you have to relentlessly stick to that same algorithm because anything else will be something else, it won’t solve the problem. Unless of course it’s another correct algorithm, but then you should probably start by changing the English version to that, sanity checking it again, and then carry on from there.

1 Like

#Write your function here
def reversed_list(lst1, lst2):
– len2 = len(lst2)
– index = 0
– index2 = (len2 - 1 - index)
– while lst1[index] == lst2[index2]:
---- return True
---- index += 1
– else:
---- return False

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

When I run my code (above) both printed lines come up as True. What am I not understanding here?

return ends the execution of the function. If the first two elements compared are ‘equal’ then ‘True’ is returned without the remaining elements being checked. You don’t want to return ‘True’ until you’ve tested every pair of elements. You can safely return ‘False’ when a single comparison fails, but you don’t know that the second list is a reversed copy of the first list until after every pair has been compared.

Gotcha. So I should put the False (does not equal) code first and then the True (does equal) after?

1 Like