FAQ: Code Challenge: Loops - Reversed List

Is this a good way to do it?
if not why not?

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

wouldn’t a simple if statement work better?

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

The one idea would be to use a naive approach and iterate over one list left to right, and the other right to left, comparing and returning False if a mismatch is found. Once the loop completes successfully, return True.

In your second example there is no logic necessary since you have a reverse slice to compare to the other list, so just return the comparison (recall that all comparisons are boolean expressions meaning they yield a boolean).

return lst1 == lst2[::-1]

Keep developing your skills to parse and manipulate lists using naive approaches so you don’t become biased toward them because of seeing this. Knowing the shortcuts doesn’t make us better prograrmmers since it blinds us to things we may not yet have learned and prevents us from dedicating the time and effort to learn them. As a beginner, we do not want to simply scratch the surface. We need to mar it and take cross-sections and examine it through every lens and portal. Not much we can do with return lst1 == lst2[::-1].

2 Likes

Can not understand. My function is returning the True and False answers (as it have to be), but system is not recognizing it.

That’s because when two empty lists are passed in there is no return value, hence None. Empty lists don’t have an index and there is no range(0).

See if this helps…

    if lst1 + lst2 == []: return True

I did it like this:

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

Tell me if it’s not ok, please. I dont want toi hit a “Solution” button :smiley:

If a mismatch is found, there is no point in completing the loop. Simply return False from inside the if block. But that aside, your code will work including on the special case the SCT tests for, reversed_list([], []). Did it not pass? What message was given in the footer of the editor?

It passed, even with empty lists
I changed my code like this:

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

That’s better?
Thanks a lot

Does it still pass the empty list test? If so, then yes, it makes more logical sense since the return False is in the loop (and the if statement).

Hello. I don’t understand why this code isn’t working:

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

Why is this returning False?

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

the reversing of your list doesn’t go well. manipulating the same list as you are looping over is very tricky

if you print lst2, you will see: [1, 2, 1]:

#Write your function here
def reversed_list(lst1, lst2):
  for i in range(len(lst2)):
    print(i, lst2[-i-1])
    
    lst2[i] = lst2[-i-1]
  print(lst2)
  if lst2 == lst1:
    return True
  else:
    return False


#Uncomment the lines below when your function is done
print(reversed_list([1, 2, 3], [3, 2, 1]))
1 Like

Ok, I’ll keep that in mind. Thanks.

I don’t understand why my code is not working for the second set of lists, where i = 1.

your code only compares the first value of lst1 with the last value of lst2, if these values are equal, true is returned else false is returned.

1 Like

I did this, which worked:

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

Seems simpler than the suggested solution. Any reason it is worse?

Hello,

Yours does solve the problem as well, I don’t think of it as a worse solution per say. In fact, I think it’s cool that people are posting alternative solutions and it helps everyone learn more.

Just that the objective of the code challenge is to practice one’s learning/understanding of loops. :slight_smile:

Hello,

After reading through the whole thread, I too, finally understand why Code 1 works to generate the correct and accurate solution instead of Code 2. This is an illustration of how it works. Please do correct me if there’s any sort of error.

e.g. - (reversed_list([1, 5, 3], [3, 2, 1]))

lst1 = [1, 5, 3]
lst2 = [3, 2, 1]

#Code 1 - Combing through list similarities with return False

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

print(reversed_list([1, 5, 3], [3, 2, 1])) #prints False *correct answer*
#Code 2 - Combing through list similarities with return True

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

print(reversed_list([1, 5, 3], [3, 2, 1])) #prints True *inaccurate answer*

Like what stetim94 mentioned:

If you use Code 2, which first uses return True to comb through similarities, it will give you inaccurate answers. Because it iterates over the value of the indices, it will return True upon the first match and stop iterating over the remaining values, which may not match 1-for-1 with the corresponding list.

Whereas if you use Code 1, which first uses return False to comb through similarities, it will stop iteration upon the first non-match of indices’ value. Else, the code will continue to run till the last index and return True for an all-matching pair of lists.

There is no point in using slicing AND a loop. Use just a loop, or just a slice.

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

Using a slice doesn’t give us much loop practice…

 return lst1 == lst2[::-1]
1 Like

Hello mtf :slight_smile:

Thanks for adding a line to as a first line of defence to check if the list has the same lengths.

Point taken for this:

1 Like


Why this code gives me true for the second print example ? It seems logical .