How can I iterate over a list backward?

Hello, @ulwianamehta-malhotr. Welcome to the forum.

return stops the execution of your function, and returns the value included in the return statement (if one exists) to the caller (the line of code that called the function). If you want your for loop to make more than one iteration, you can’t can’t return anything until it is finished. See this post for an additional explanation: FAQ: Code Challenge: Loops - Reversed List
Happy coding!

Also, please use the </> button in the menu bar above where you type to format your code. This is especially important with Python where indentation is not optional. Click the </> button first on a blank line, and then paste your code in the space indicated.
Thanks!

Hi! I figured it out! The unindent actually takes the place of an else statement. It means the same thing!

Sorry, can you explain the rules of this game please? I could not find it by the name…Is it correct that we can’t see the numbers until we “flip them from the right hand side”? Or we just need to find the correct place for the end number in the random list?

can someone clear me how can we create a new list (that contains values and that contains indices of the values) from comparing 2 lists ?
for example if we have 2 lists [5,9,23,12] and [1,9,3,12] how can we create a list of same values i.e [9,12] (values) and list of indices of same values i.e [1,3] (indices)? Please
Thanks

It’s been decades since I first heard of this game.

Think of a scrambled list of numbers, starting with lowest difficulty, three digits.

3 1 2

Flipping only from the right, we would select the 1 and flip the pair, which will give

3 2 1

Now flip all three and we have the complete order,

1 2 3

Next we got up one digit,

2 4 3 1

The first flip will be all four,

1 3 4 2

Next flip the right three,

1 2 4 3

Then the final flip, the last two digits,

1 2 3 4

Now five digits, which illustrates multiple possible strategies.

4 1 5 2 3

4 1 5 3 2

4 1 2 3 5

5 3 2 1 4

5 4 1 2 3

5 4 3 2 1

1 2 3 4 5

That took five flips. Can we do it in less?

4 1 5 2 3

4 1 3 2 5

5 2 3 1 4

5 4 1 3 2

5 4 1 2 3

5 4 3 2 1

1 2 3 4 5

Also five flips.

The game continues up to nine digits. A score less than,

(3 + 9) / 2 * 7 => 6 * 7 => 42

is considered below par. Like in golf, the lower the score the better.

1 Like

Since we want (I’m assuming) only matches at the same index we can create a zip object of paired values.

>>> a, b = [5, 9, 23, 12], [1, 9, 3, 12]
>>> c = zip(a, b)
>>> d = []
>>> for m, n in c:
	if m == n:
		d.append(m)

		
>>> d
[9, 12]
>>> 

If you are not familiar with the zip constructor, it essentially merges two or more lists into a list of tuples.

>>> c
[(5, 1), (9, 9), (23, 3), (12, 12)]
>>> 

When we iterate a zip object all we need is enough variables to be able to unpack each tuple, in this case two,

for m, n in c:

This may be new to you, too. Consider,

x = (3, 5, 7, 9)

a, b, c, d = x

print a    # 3
print b    # 5
print c    # 7
print d    # 9

list objects can be unpacked in the exact same way. Of course the shorter the sequence the more it makes sense to unpack, where a longer sequence is better iterated than unpacked so there are not a lot of variables in play.

At some point you will learn about comprehensions, if not already learned. We can write a single line solution to the problem which returns a list…

>>> a, b = [5, 9, 23, 12], [1, 9, 3, 12]
>>> [m for m, n in zip(a, b) if m == n]
[9, 12]
>>> 

It follows that we could write this as a reusable function…

def matched_pairs(a, b):
    return [m for m, n in zip(a, b) if m == n]

print (matched_pairs([5, 9, 23, 12], [1, 9, 3, 12]))
# [9, 12]
print (matched_pairs([12, 16, 20, 24, 28], [4, 5, 20, 21, 28]))
# [20, 28]

!!! Thank you!! It’s so interesting!

Sorry, seems too much information for my poor head for the moment, but I can’t stand: what formula did you use? Why?

It’s a sequence sum formula…

     n
S = --- (a + k)
     2

where,

n => number of terms in the sequence

a => first term in the sequence

k => last term in sequence

The sequence has a common difference (d) between terms, in this case, d == 1

3 4 5 6 7 8 9 => n == 7

3 + 9         => a + k == 12

Above I divided by 2 first since 12 is an even number, which gives 6. Multiplied by 7 gives 42.

3 + 4 =>  7
5 + 6 => 11
7 + 8 => 15
        + 9
        ----
         42

it worked for me :

#Write your function here
def reversed_list(lst1, lst2):
index=0
reversed1=
reversed2=
index2=len(lst1)-1
while index < (len(lst1)):

reversed1.append(lst1[index])
reversed2.append(lst2[index2])
index2-=1
index+=1

if reversed1 == reversed2:
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]))

I know this is old, but I’m really not understanding how this line is returning the correct index position. I know it’s lst2[-1] that starts at the right most index, I don’t understand how the length of the list subtract 1 subtract the index variable will result in the corresponding index position for lst1.

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

I get it visually when looking at the list, but it’s confusing as to how this more dynamic formula results in the corresponding index position of lst1.

>>> a = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> len(a)
11
>>> a[0]
0
>>> a[-11]
0
>>> 

We’re comparing two lists that might be the exact reverse of each other. That means,

>>> b = [55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]
>>> b[-11] == a[0]
True

Thank you for the explanation. I see, that makes much more sense. I think I was overthinking it. The index positions make sense, it was calculating the index position. In this case it’d be the index position of list b in your example.

1 Like

When both lists are the same length, then,

b[n] == a[m]

when,

abs(n) + abs(m) == len(a) == len(b)

This can be proven by your math.

>>> a = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> b = [55, 34, 21, 13, 8, 5, 3, 2, 1, 1, 0]

Unless we first reverse one of the lists, >>> b[-11] == a[0] would be False.

>>> b[-11]
55
>>> a[0]
0

If the lists are the exact reverse of each other, >>> b[-1] == a[0] would be True.

1 Like

D’oh! Is it a typo? Maybe. Can’t argue that you are correct, though. It’s what I get for not double checking, a lesson all would-be programmers can learn from. Thanks for catching this.

You bet. I assumed it was probably a typo. :wink:

1 Like

This one worked for me

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

Hi all, I dont understand why my code is returning True in both scenarios:

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

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

If my maths are correct:
In the first iteration -1-index == -1 #being index == 0
In the second iteration -1-index == -2 #being index == 1
In the third iteration -1-index == -3 #being index == 2
Beats me

does this iteration happen? Have you verified that?

there is nothing with your maths, but in the first iteration of the loop, a return keyword is reached, which means the function hands back data, and has done its job. So you never get to the second iteration

this also means, only the first value of lst1 and last value of lst2 are compared, and based on that data only, determines if the lists are opposite/reverses of each other